protected DataView GetVenueEvents()
    {
        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", ":")));
        string id = Request.QueryString["ID"].ToString();

        DataView dvNormal = dat.GetDataDV("SELECT EO.DateTimeStart AS Start, EO.DateTimeEnd AS " +
            "[End], E.Header, CONVERT(NVARCHAR,E.ID)+';E;'+CONVERT(NVARCHAR,EO.ID) AS ID, V.Name "+
            "FROM Event_Occurance EO, Events E, Venues " +
            "V WHERE EO.EventID=E.ID AND E.Venue=V.ID AND V.ID=" + id);

        DataView dvGroupPublic = dat.GetDataDV("SELECT EO.DateTimeStart AS Start, EO.DateTimeEnd AS " +
            "[End], E.Name AS Header, CONVERT(NVARCHAR,E.ID)+';G;'+CONVERT(NVARCHAR,EO.ID) AS ID, EO.ID "+
            "AS ReoccurrID, V.Name FROM GroupEvent_Occurance EO, GroupEvents E, Venues " +
            "V WHERE E.EventType='1' AND EO.GroupEventID=E.ID AND EO.VenueID=V.ID AND V.ID=" + id);

        DataView dvGroupInvited = new DataView();
        if (Session["User"] != null)
        {
            dvGroupInvited = dat.GetDataDV("SELECT EO.DateTimeStart AS Start, EO.DateTimeEnd AS " +
            "[End], E.Name AS Header,  CONVERT(NVARCHAR,E.ID)+';G;'+CONVERT(NVARCHAR,EO.ID) AS ID, EO.ID " +
            "AS ReoccurrID, V.Name FROM GroupEvent_Occurance EO, GroupEvents E, GroupEvent_Members GEM, Venues " +
            "V WHERE E.EventType <> '1' AND GEM.UserID=" + Session["User"].ToString() + " AND GEM.GroupEventID=E.ID AND GEM.ReoccurrID=EO.ID " +
            "AND EO.GroupEventID=E.ID AND EO.VenueID=V.ID AND V.ID=" + id);
        }

        return MergeDV(MergeDV(dvGroupPublic, dvGroupInvited), dvNormal);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            HtmlMeta hm = new HtmlMeta();
            HtmlHead head = (HtmlHead)Page.Header;
            hm.Name = "ROBOTS";
            hm.Content = "NOINDEX, FOLLOW";
            head.Controls.AddAt(0, hm);
            HttpCookie cookie = Request.Cookies["BrowserDate"];
            Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

            DataView dvGroupEvent = dat.GetDataDV("SELECT * FROM GroupEvents WHERE ID=" + Request.QueryString["ID"].ToString());
            ImageButton9.OnClientClick = "javascript:Search('" +
                dat.MakeNiceName(dvGroupEvent[0]["Name"].ToString()) + "_" + Request.QueryString["O"].ToString() + "_" +
                Request.QueryString["ID"].ToString() + "_GroupEvent');";

            string groupID = Request.QueryString["ID"].ToString();
            string command = "SELECT * FROM Group_Members WHERE GroupID=" +
               dvGroupEvent[0]["GroupID"].ToString() + " AND MemberID=" + Session["User"].ToString();
            DataView dvMembers = dat.GetDataDV(command);
            if (bool.Parse(dvMembers[0]["SharedHosting"].ToString()))
            {
                HostPanel.Visible = true;
            }
            else
                HostPanel.Visible = false;
        }
        catch (Exception ex)
        {
            ErrorLabel.Text = ex.ToString();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlMeta hm = new HtmlMeta();
        HtmlHead head = (HtmlHead)Page.Header;
        hm.Name = "ROBOTS";
        hm.Content = "NOINDEX, FOLLOW";
        head.Controls.AddAt(0, hm);

        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);
        }
        //Ajax.Utility.RegisterTypeForAjax(typeof(Delete));
        if (!IsPostBack)
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];
            Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
            DataView dvEvent = dat.GetDataDV("SELECT * FROM GroupEvents WHERE ID=" +
                Request.QueryString["ID"].ToString());
            string groupID = dvEvent[0]["GroupID"].ToString();
            DataView dvGroup = dat.GetDataDV("SELECT * FROM Groups WHERE ID=" + groupID);
            ImageButton9.OnClientClick = "Search('" + dat.MakeNiceName(dvGroup[0]["Header"].ToString()) + "_" + groupID + "_Group');";

            TextLabel.Text = "Are you sure you want to delete the event '" + dvEvent[0]["Name"].ToString() +
                "' from the group '" + dvGroup[0]["Header"].ToString() + "'";
        }
    }
    protected void CheckAndInsert(string header, string description, string date, string images, string VenueID, string categories, string URL)
    {
        Data dat = new Data(DateTime.Now);

        //Check whether event exists in database
        DateTime dStart = DateTime.Parse(date);
        DataView dvEvent = dat.GetDataDV("SELECT * FROM Events E, Event_Occurance EO WHERE E.Venue=" + VenueID +
            " AND E.Header='" + header + "' AND E.ID=EO.EventID AND EO.DateTimeStart = CONVERT(DATETIME, '" + dStart.ToString() + "')");
        //Insert if does not exist
        if (dvEvent.Count == 0)
        {
            DataView dvVenue = dat.GetDataDV("SELECT country, city, state, zip, address FROM Venues WHERE ID=" + VenueID);
            string country = dvVenue[0]["country"].ToString();
            string city = dvVenue[0]["city"].ToString();
            string state = dvVenue[0]["state"].ToString();
            string zip = dvVenue[0]["zip"].ToString();
            string address = dvVenue[0]["address"].ToString();

            string mediaCat = "0";
            if (images != "")
                mediaCat = "1";

            if (description.Length > 500)
                description = description.Substring(0, 500) + "... " + URL;

            dvEvent = dat.GetDataDV("INSERT INTO Events (PostedOn, LastEditOn, UserName, Venue, Header, [Content], StarRating, hasSongs, mediaCategory, " +
                "city, country, state, zip, address) VALUES ('" + DateTime.Now.ToString() + "', '" + DateTime.Now.ToString() + "', 'aleksczajka', " +
                VenueID + ", '" + header +
                "', '" + description.Replace("'", "''").Replace("\\", "\\\\") + "', 0, 'False', " + mediaCat + ", '" + city + "', " +
                country + ", '" + state + "', '" + zip + "', '" + address + "')  SELECT @@IDENTITY AS 'Identity'");

            string theID = dvEvent[0]["Identity"].ToString();

            //Insert date and time
            dat.Execute("INSERT INTO Event_Occurance (EventID, DateTimeStart, DateTimeEnd) VALUES (" + theID + ", '" +
                dStart.ToString() + "', '" + dStart.AddHours(2.00).ToString() + "')");

            //Insert categories
            string[] delim = { ";" };
            string[] tokens = categories.Split(delim, StringSplitOptions.RemoveEmptyEntries);
            foreach (string token in tokens)
            {
                dat.Execute("INSERT INTO Event_Category_Mapping (CategoryID, EventID, tagSize) VALUES (" + token + ", '" +
                    theID + "', 22)");
            }

            //Insert Images
            string[] imgDelim = { "^" };
            if (images != "")
            {
                string[] imgTokens = images.Split(imgDelim, StringSplitOptions.RemoveEmptyEntries);
                foreach (string token in imgTokens)
                {
                    dat.Execute("INSERT INTO Event_Slider_Mapping (EventID, PictureName, RealPictureName, " +
                        "ImgPathAbsolute) VALUES(" + theID + ", '" + token + "', '" + token + "', 'True')");
                }
            }
        }
    }
    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", ":")));

        HtmlMeta hm = new HtmlMeta();
        HtmlHead head = (HtmlHead)Page.Header;
        hm.Name = "ROBOTS";
        hm.Content = "NOINDEX, FOLLOW";
        head.Controls.AddAt(0, hm);

        HtmlLink lk = new HtmlLink();
        lk.Attributes.Add("rel", "canonical");
        lk.Href = "http://hippohappenings.com/HippoPointsEdit.aspx";
        head.Controls.AddAt(0, lk);

        UploadButton.SERVER_CLICK += UploadPick;
        PictureNixItButton.SERVER_CLICK += NixIt;
        BlueButton2.SERVER_CLICK += Save;

        ErrorLabel.Text = "";

        Literal lit = new Literal();
        lit.Text = dat.GetDataDV("SELECT * FROM HippoPointsConditions")[0]["Content"].ToString();

        TACTextBox.Controls.Add(lit);

        if (!IsPostBack)
        {
            DataView dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP WHERE UP.UserID=" + Session["User"].ToString());

            if(dvUser[0]["MayorText"].ToString().Trim() != "")
                DescriptionTextBox.Text = dvUser[0]["MayorText"].ToString();

            Checkbox1.Checked = bool.Parse(dvUser[0]["Mayors"].ToString());

            if (dvUser[0]["PictureName"].ToString().Trim() != "")
            {
                TheImage.ImageUrl = dvUser[0]["PictureName"].ToString();
                PictureNixItButton.Visible = true;
            }

            if (dvUser[0]["MayorLink"].ToString().Trim() != "")
            {
                LinkTextBox.Text = dvUser[0]["MayorLink"].ToString();
            }
        }
    }
    protected void AutomaticJoin(object sender, EventArgs e)
    {
        try
        {
            HttpCookie cookie = Request.Cookies["BrowserDate"];
            Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

            string shared = "False";
            string title = "";
            string prefs = "124";
            DataView dvGroup = dat.GetDataDV("SELECT * FROM Groups WHERE AutomaticHost='True' " +
                "AND ID=" + Request.QueryString["ID"]);

            if (dvGroup.Count > 0)
            {
                shared = "True";
                title = "Shared Host";
                prefs = "12345";
            }

            dat.Execute("INSERT INTO Group_Members (GroupID, MemberID, Title, SharedHosting, Accepted, Prefs) " +
                "VALUES(" + Request.QueryString["ID"] + ", " + Session["User"].ToString() +
                ", '" + title + "', '" + shared + "', 'True', " + prefs + ")");

            AutomaticPanel.Visible = false;
            ThankYouPanel.Visible = true;
        }
        catch (Exception ex)
        {
            Label1.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", ":")));
        if (Session["User"] == null)
        {
            Response.Redirect("~/Home.aspx");

        }

        if (Request.QueryString["ID"] == null)
            Response.Redirect("Home.aspx");

        if (dat.HasEventPassed(Request.QueryString["ID"].ToString()))
        {
            DataView dvName = dat.GetDataDV("SELECT * FROM Events WHERE ID="+
                Request.QueryString["ID"].ToString());
            Response.Redirect(dat.MakeNiceName(dvName[0]["Header"].ToString()) + "_" +
                Request.QueryString["ID"].ToString() + "_Event");
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlMeta hm = new HtmlMeta();
        HtmlHead head = (HtmlHead)Page.Header;
        hm.Name = "ROBOTS";
        hm.Content = "NOINDEX, FOLLOW";
        head.Controls.AddAt(0, hm);

        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", ":")));

        DataView dvGroup = dat.GetDataDV("SELECT * FROM Groups WHERE ID="+Request.QueryString["ID"].ToString());
        if (dvGroup[0]["Host"].ToString() == Session["User"].ToString())
        {
            TheLabel.Text = "Since you are the primary host of the group, you must first designate another host for the group. Go to your group's home page and click on 'Edit Members' Prefs'.";
            Button3.Visible = false;
        }
    }
    protected void DrawEvents(DataView dvEvents, int cutOff)
    {
        string eventID = GetEventID();
        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 isNow = DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"));
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        Literal lit = new Literal();

        int count = 0;
        DataView dvEvent;
        string contentSub = "";
        foreach (DataRowView row in dvEvents)
        {
            if (count > cutOff - 1)
            {
                break;
            }
            else
            {
                contentSub = dat.stripHTML(row["Content"].ToString().Replace("<br>",
                    "").Replace("</br>", "").Replace("<br/>", "").Replace("<BR>", "").Replace("<BR/>",
                    "").Replace("<br />", "").Replace("<BR />", ""));
                if (dat.stripHTML(row["Content"].ToString().Replace("<br>",
                    "").Replace("</br>", "").Replace("<br/>", "").Replace("<BR>", "").Replace("<BR/>",
                    "").Replace("<br />", "").Replace("<BR />", "")).Length > 100)
                    contentSub = dat.stripHTML(row["Content"].ToString().Replace("<br>",
                        "").Replace("</br>", "").Replace("<br/>", "").Replace("<BR>", "").Replace("<BR/>",
                        "").Replace("<br />", "").Replace("<BR />", "")).Substring(0, 100);
                dvEvent = dat.GetDataDV("SELECT * FROM Events E, Event_Occurance EO WHERE E.ID=EO.EventID AND E.ID=" + row["EventID"].ToString());
                lit.Text += "<div class=\"SimilarSide\">";
                lit.Text += "<a class=\"Blue12Link\" href=\"" + dat.MakeNiceName(row["Header"].ToString()) +
                    "_" + row["EventID"].ToString() + "_Event\">" + row["Header"].ToString() +
                    "</a> at " + "<a class=\"Green12LinkNF\" href=\"" + dat.MakeNiceName(row["Name"].ToString()) +
                    "_" + row["Venue"].ToString() + "_Venue\">" + row["Name"].ToString() + "</a> on " +
                    DateTime.Parse(dvEvent[0]["DateTimeStart"].ToString()).ToShortDateString() +
                    ". " + dat.BreakUpString(contentSub, 30) +
                    "... <a class=\"Blue12Link\" href=\"" + dat.MakeNiceName(row["Header"].ToString()) +
                    "_" + row["EventID"].ToString() + "_Event\">Read More</a>";
                lit.Text += "</div>";
                count++;
            }
        }

        OtherEventsPanel.Controls.Add(lit);
    }
    protected void CheckMayors()
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        DateTime isNow = DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"));
        Data dat = new Data(isNow);
        string thisMonth = isNow.Month.ToString() + "/1/" + isNow.Year.ToString();
        string userID = Request.QueryString["ID"].ToString();
        DataView dvUser = dat.GetDataDV("SELECT * FROM Users WHERE User_ID=" + userID);
        DataView dv = dat.GetDataDV("SELECT * FROM UserPreferences WHERE UserID=" + userID);

        //Happenings
        DataView dvEventCount = dat.GetDataDV("SELECT COUNT(*) AS count  FROM Events WHERE UserName='******'");

        DataView dvEventCountLast = dat.GetDataDV("SELECT COUNT(*) AS count FROM Events WHERE PostedOn >= CONVERT(DATETIME,'" +
            thisMonth + "') AND UserName='******'");
        NumEventsLabel.Text = "<span class=\"TextNormal Friend20\">" + dvEventCount[0]["count"].ToString() +
            "</span> Happenings. <span class=\"TextNormal Friend20\">" + dvEventCountLast[0]["count"].ToString() +
            "</span> This Month.";

        //Trips
        dvEventCount = dat.GetDataDV("SELECT COUNT(*) AS count  FROM Trips WHERE UserName='******'");

        dvEventCountLast = dat.GetDataDV("SELECT COUNT(*) AS count  FROM Trips WHERE PostedOn >= CONVERT(DATETIME,'" +
            thisMonth + "') AND UserName='******'");
        NumTripsLabel.Text = "<span class=\"TextNormal Friend20\">" + dvEventCount[0]["count"].ToString() +
            "</span> Trips. <span class=\"TextNormal Friend20\">" + dvEventCountLast[0]["count"].ToString() +
            "</span> This Month.";

        //Locales
        dvEventCount = dat.GetDataDV("SELECT COUNT(*) AS count  FROM Venues WHERE CreatedByUser="******"SELECT COUNT(*) AS count  FROM Venues WHERE PostedOn >= CONVERT(DATETIME,'" +
            thisMonth + "') AND CreatedByUser="******"<span class=\"TextNormal Friend20\">" + dvEventCount[0]["count"].ToString() +
            "</span> Locales. <span class=\"TextNormal Friend20\">" + dvEventCountLast[0]["count"].ToString() +
            "</span> This Month.";

        //Ads
        dvEventCount = dat.GetDataDV("SELECT COUNT(*) AS count  FROM Ads WHERE User_ID=" + userID);

        dvEventCountLast = dat.GetDataDV("SELECT COUNT(*) AS count  FROM Ads WHERE DateAdded >= CONVERT(DATETIME,'" +
            thisMonth + "') AND User_ID=" + userID);
        NumAdsLabel.Text = "<span class=\"TextNormal Friend20\">" + dvEventCount[0]["count"].ToString() +
            "</span> Bulletins. <span class=\"TextNormal Friend20\">" + dvEventCountLast[0]["count"].ToString() +
            "</span> This Month.";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        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);
        }
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":").Replace("%28", "(").Replace("%29", ")")));

        DataView dv = dat.GetDataDV("SELECT * FROM TermsAndConditions");

        testLit.Text = dv[0]["Content"].ToString();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlMeta hm = new HtmlMeta();
        HtmlHead head = (HtmlHead)Page.Header;
        hm.Name = "ROBOTS";
        hm.Content = "NOINDEX, FOLLOW";
        head.Controls.AddAt(0, hm);
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        DataView dvGroupEvent = dat.GetDataDV("SELECT * FROM GroupEvents WHERE ID=" +
            Request.QueryString["ID"].ToString());

        ImageButton9.OnClientClick = "javascript:Search('" +
            dat.MakeNiceName(dvGroupEvent[0]["Name"].ToString()) + "_" + Request.QueryString["O"].ToString() + "_" +
            Request.QueryString["ID"].ToString() + "_GroupEvent');";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        HtmlMeta hm = new HtmlMeta();
        HtmlHead head = (HtmlHead)Page.Header;
        hm.Name = "ROBOTS";
        hm.Content = "NOINDEX, FOLLOW";
        head.Controls.AddAt(0, hm);

        ImageButton9.OnClientClick = "javascript:Search('Group.aspx?ID=" +
            Request.QueryString["ID"].ToString() + "');";

        DataView dvGroup = dat.GetDataDV("SELECT * FROM Groups WHERE AutomaticAccept='True' "+
            "AND ID=" + Request.QueryString["ID"]);

        if (Session["User"] == null)
        {
            RemovePanel.Visible = false;
            NotSignedInPanel.Visible = true;
            AutomaticPanel.Visible = false;
        }
        else
        {

            if (dvGroup.Count == 0)
            {

                NotSignedInPanel.Visible = false;
                RemovePanel.Visible = true;
                AutomaticPanel.Visible = false;
            }
            else
            {
                ThankYouLabel.Text = "You have joined the group.";
                AutomaticPanel.Visible = true;
                NotSignedInPanel.Visible = false;
                RemovePanel.Visible = false;
            }
        }
    }
    protected DataView GetVenueEvents()
    {
        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", ":")));
        string id = Request.QueryString["ID"].ToString();

        DataView dvNormal = dat.GetDataDV("SELECT EO.DateTimeStart AS Start, EO.DateTimeEnd AS " +
            "[End], E.Header, CONVERT(NVARCHAR,E.ID)+';E;'+CONVERT(NVARCHAR,EO.ID) AS ID, V.Name "+
            "FROM Event_Occurance EO, Events E, Venues " +
            "V WHERE EO.EventID=E.ID AND E.Venue=V.ID AND V.ID=" + id);

        return dvNormal;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlMeta hm = new HtmlMeta();
        HtmlHead head = (HtmlHead)Page.Header;
        hm.Name = "ROBOTS";
        hm.Content = "NOINDEX, FOLLOW";
        head.Controls.AddAt(0, hm);

        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", ":")));

        DataView dvGroup = dat.GetDataDV("SELECT * FROM Users WHERE User_ID=" + Request.QueryString["ID"].ToString());

        TheLabel.Text = " Are you sure you want to remove your friend '" + dvGroup[0]["UserName"].ToString() + "'?";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlMeta hm = new HtmlMeta();
        HtmlHead head = (HtmlHead)Page.Header;
        hm.Name = "ROBOTS";
        hm.Content = "NOINDEX, FOLLOW";
        head.Controls.AddAt(0, hm);

        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);
        }
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":").Replace("%28", "(").Replace("%29", ")")));

        DataView dv = dat.GetDataDV("SELECT * FROM TermsAndConditions");

        testLit.Text = dv[0]["Content"].ToString();
    }
    protected void DeleteEventAction(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        if (JustInstanceCheck.Checked)
        {
            dat.Execute("DELETE FROM GroupEvent_Occurance WHERE ID=" + Request.QueryString["O"].ToString());
            DataView dv = dat.GetDataDV("SELECT * FROM GroupEvent_Occurance WHERE GroupEventID=" +
                Request.QueryString["ID"].ToString());
            if(dv.Count == 0)
                dat.Execute("UPDATE GroupEvents SET LIVE='False' WHERE ID=" +
                    Request.QueryString["ID"].ToString());
        }
        else
        {
            dat.Execute("UPDATE GroupEvents SET LIVE='False' WHERE ID=" + Request.QueryString["ID"].ToString());
        }

        RemovePanel.Visible = false;
        ThankYouPanel.Visible = true;
    }
    protected void CreateCategories(string ID, string Categories)
    {
        char[] delim = { ';' };
        string[] tokens = Categories.Split(delim);

        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        string catID = "";
        string size = "22";
        if (Categories.Trim() != "")
        {
            for (int i = 0; i < tokens.Length; i++)
            {
                DataView dvC = dat.GetDataDV("SELECT * FROM EventCategories WHERE Name = '" +
                    tokens[i] + "'");

                if (dvC.Count > 0)
                {
                    catID = dvC[0]["ID"].ToString();

                    if (dvC[0]["ParentID"] != null && dvC[0]["ParentID"].ToString() != "")
                        size = "16";
                    else
                        size = "22";

                    if (catID != null)
                    {
                        if (tokens[i].Trim() != "")
                        {
                            dat.Execute("INSERT INTO Event_Category_Mapping (CategoryID, EventID, tagSize) VALUES("
                                        + catID + "," + ID + ", " + size + ")");
                        }
                    }
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Data dat = new Data(DateTime.Now);

        if(Request.QueryString["ID"] == null)
            Response.Redirect("../home");

        string theID = Request.QueryString["ID"].ToString();

        DataView dv = dat.GetDataDV("SELECT * FROM HippoBlogContent WHERE ID=" + theID);

        TitleLiteral.Text = dv[0]["Title"].ToString();
        TagLineLiteral.Text = dv[0]["TagLine"].ToString();
        MainContentLiteral.Text = dv[0]["MainContent"].ToString();

        MainImage.Visible = false;
        if (dv[0]["MainImage"].ToString() != "")
        {
            MainImage.ImageUrl = dv[0]["MainImage"].ToString();
            MainImage.Visible = true;
        }

        Page.Title = dat.MakeNiceName(dv[0]["Title"].ToString());
    }
    protected void LoadCustomAlert()
    {
        try
        {
            HttpCookie cookie = Request.Cookies["BrowserDate"];

            Data d = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
            DataView dvAlerts = d.GetDataDV("SELECT * FROM UserEventAlerts WHERE UserID=" +
                       Session["User"].ToString() + " AND EventID=" + Request.QueryString["EID"].ToString());

            if (dvAlerts.Count > 0)
            {
                if (bool.Parse(dvAlerts[0]["ON"].ToString()))
                {
                    AlertRadioList.Items[0].Selected = true;
                    AlertRadioList.Items[1].Selected = false;
                }
                else
                {
                    AlertRadioList.Items[0].Selected = false;
                    AlertRadioList.Items[1].Selected = true;
                }

                if (dvAlerts[0]["MHDWNumb"] != null)
                {
                    if (dvAlerts[0]["MHDWNumb"].ToString().Trim() != "")
                    {
                        TimeCheck.Checked = true;
                        TimeTextBox.Text = dvAlerts[0]["MHDWNumb"].ToString();
                        TimeDropDown.SelectedValue = dvAlerts[0]["MHDW"].ToString();
                    }
                }
                else
                {
                    TimeCheck.Checked = false;
                    TimeTextBox.Text = "";
                    TimeDropDown.ClearSelection();
                }

                if (dvAlerts[0]["RepeatMHDWNumb"] != null)
                {
                    if (dvAlerts[0]["RepeatMHDWNumb"].ToString().Trim() != "")
                    {
                        RepeatCheck.Checked = true;
                        RepeatTextBox.Text = dvAlerts[0]["RepeatMHDWNumb"].ToString();
                        RepeatDropDown.SelectedValue = dvAlerts[0]["RepeatMHDW"].ToString();
                    }
                }
                else
                {
                    RepeatCheck.Checked = false;
                    RepeatTextBox.Text = "";
                    RepeatDropDown.ClearSelection();
                }

                EndedCheck.Checked = bool.Parse(dvAlerts[0]["AlertWhenEnded"].ToString());

                EmailCheck.Checked = bool.Parse(dvAlerts[0]["isEmail"].ToString());

                TextCheck.Checked = bool.Parse(dvAlerts[0]["isText"].ToString());

                DateTime nowTime = DateTime.Now;
                if (nowTime.Second > 30)
                    nowTime = nowTime.AddSeconds(60 - nowTime.Second);
                else
                    nowTime = nowTime.AddSeconds(-nowTime.Second);

            }
            else
            {
                AlertRadioList.Items[0].Selected = false;
                AlertRadioList.Items[1].Selected = false;

                TimeCheck.Checked = false;
                TimeTextBox.Text = "";
                TimeDropDown.ClearSelection();

                RepeatCheck.Checked = false;
                RepeatTextBox.Text = "";
                RepeatDropDown.ClearSelection();

                EndedCheck.Checked = false;

                EmailCheck.Checked = false;

                TextCheck.Checked = false;
            }
        }
        catch (Exception ex)
        {
            MessageLabel.Text = ex.ToString();
        }
    }
    protected void SaveSettingsDB(object sender, EventArgs e)
    {
        string message = "";
        try
        {
            HttpCookie cookie = Request.Cookies["BrowserDate"];

            Data d = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            //save custom alert preferences
            DataView dvAlerts = d.GetDataDV("SELECT * FROM UserEventAlerts WHERE UserID=" +
                       Session["User"].ToString() + " AND ReoccurID=" +
                       Request.QueryString["RID"].ToString() + " AND EventID=" +
                       Request.QueryString["EID"].ToString());
            bool execute = false;

            if (!TextCheck.Checked && !EmailCheck.Checked)
            {
                message = "Please check 'Email', 'Text', or both for this alert.";
                execute = false;
            }
            else
            {
                if (dvAlerts.Count > 0)
                {
                    if (TimePicker.DbSelectedDate != null)
                    {
                        cmd = new SqlCommand("UPDATE UserEventAlerts SET MHDW=@mhdw, MHDWNumb=@mhdwNum, " +
                           "RepeatMHDW=@repeatMHDW, LastRan=@lastRun, RepeatMHDWNumb=@repeatMHDWNum, AlertWhenEnded=@ended, " +
                           "isEmail=@email, isText=@text, [On]=@on, ServerTimeDifference=@time WHERE UserID=" +
                           Session["User"].ToString() + " AND isAllEvents = 'False' AND EventID=" + Request.QueryString["EID"].ToString(), conn);
                        execute = true;
                    }
                    else
                    {
                        message = "The time in your location is required.";
                        execute = false;
                    }
                }
                else if (TimeCheck.Checked || RepeatCheck.Checked || EndedCheck.Checked)
                {
                    if (TimePicker.DbSelectedDate != null)
                    {
                        execute = true;
                        cmd = new SqlCommand("INSERT INTO UserEventAlerts (ReoccurID, EventID, UserID, MHDW, MHDWNumb, " +
                            "RepeatMHDW, RepeatMHDWNumb, AlertWhenEnded, " +
                            "isEmail, isText, [On], isAllEvents,ServerTimeDifference) VALUES (" +
                            Request.QueryString["RID"].ToString() + ", " +
                            Request.QueryString["EID"].ToString() + ", " +
                            Session["User"].ToString() + ",@mhdw, @mhdwNum, @repeatMHDW, " +
                            "@repeatMHDWNum, @ended, @email, @text, @on, 'False', @time)", conn);
                    }
                    else
                    {
                        message = "The time in your location is required.";
                        execute = false;
                    }
                }
                else
                {
                    message = "You must enter alert criteria.";
                    execute = false;
                }
            }

            if (execute)
            {
                if (TimeCheck.Checked && TimeTextBox.Text.Trim() != "")
                {
                    cmd.Parameters.Add("@mhdw", SqlDbType.Int).Value = TimeDropDown.SelectedValue;
                    cmd.Parameters.Add("@mhdwNum", SqlDbType.Int).Value = int.Parse(TimeTextBox.Text.Trim());
                }
                else
                {
                    cmd.Parameters.Add("@mhdw", SqlDbType.Int).Value = DBNull.Value;
                    cmd.Parameters.Add("@mhdwNum", SqlDbType.Int).Value = DBNull.Value;
                }

                if (RepeatCheck.Checked && RepeatTextBox.Text.Trim() != "")
                {
                    cmd.Parameters.Add("@repeatMHDW", SqlDbType.Int).Value = RepeatDropDown.SelectedValue;
                    cmd.Parameters.Add("@repeatMHDWNum", SqlDbType.Int).Value = int.Parse(RepeatTextBox.Text.Trim());
                }
                else
                {
                    cmd.Parameters.Add("@repeatMHDW", SqlDbType.Int).Value = DBNull.Value;
                    cmd.Parameters.Add("@repeatMHDWNum", SqlDbType.Int).Value = DBNull.Value;
                }

                cmd.Parameters.Add("@lastRun", SqlDbType.DateTime).Value = DBNull.Value;
                cmd.Parameters.Add("@ended", SqlDbType.Bit).Value = EndedCheck.Checked;
                cmd.Parameters.Add("@email", SqlDbType.Bit).Value = EmailCheck.Checked;
                cmd.Parameters.Add("@text", SqlDbType.Bit).Value = TextCheck.Checked;
                cmd.Parameters.Add("@on", SqlDbType.Bit).Value = AlertRadioList.Items[0].Selected;

                message += TimePicker.DbSelectedDate.ToString();

                DateTime timNow = DateTime.Parse(TimePicker.DbSelectedDate.ToString());
                DateTime nowTime = DateTime.Now;
                if (nowTime.Second > 30)
                    nowTime = nowTime.AddSeconds(60 - nowTime.Second);
                else
                    nowTime = nowTime.AddSeconds(-nowTime.Second);

                TimeSpan timeDiff = nowTime - timNow;

                cmd.Parameters.Add("@time", SqlDbType.Int).Value = timeDiff.TotalSeconds;

                cmd.ExecuteNonQuery();

                MessageLabel.Text = "Your alert has been saved";
            }
            else
            {
                MessageLabel.Text = message;
            }
        }
        catch (Exception ex)
        {
            MessageLabel.Text = message + "<br/>" + ex.ToString();
        }
    }
    protected void PostItVenue(DataRowView row)
    {
        bool cont = true;
        if (row["product_name"].ToString().Contains("duplicate do not use") || row["State"].ToString().Trim() == ""
             || row["Street"].ToString().Trim() == "")
            cont = false;

        if (cont)
        {
            HttpCookie cookie = Request.Cookies["BrowserDate"];
            string problem = "";
            try
            {
                StatusPanel.Text += "got inside";
                Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
                string email = "";
                string textEmail = "";
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
                conn.Open();

                //this means there is no pictures or videos

                DataView dvStreets = dat.GetDataDV("SELECT * FROM Streets");

                DataSet dsEvent = new DataSet();
                string theCat = "NULL";

                string command = "";

                #region Create/Assign Venue
                string venue = "";
                bool isNewVenue = false;
                int venueID = 0;
                string country = "";
                string state1 = "";

                //User created a new venue. Must save it.

                venue = row["product_name"].ToString();
                isNewVenue = true;
                bool goNext = true;
                SqlCommand cmd2;

                if (goNext)
                {
                    cmd2 = new SqlCommand("INSERT INTO Venues (Content, Name, Address, Country, State, City, Zip, " +
                        "MediaCategory, CreatedByUser, Edit, Rating, TixMasterCode, PostedOn, LastEditOn) VALUES (@content, @vName, @address, @country, "+
                        "@state, @city, @zip, 0, @user, 'True', 0, @thecode, GETDATE(), GETDATE())", conn);
                    cmd2.Parameters.Add("@vName", SqlDbType.NVarChar).Value = venue;
                    cmd2.Parameters.Add("@user", SqlDbType.Int).Value = 42;
                    cmd2.Parameters.Add("@country", SqlDbType.Int).Value = 223;
                    cmd2.Parameters.Add("@city", SqlDbType.NVarChar).Value = row["City"].ToString();
                    cmd2.Parameters.Add("@zip", SqlDbType.NVarChar).Value = row["ZipCode"].ToString();
                    cmd2.Parameters.Add("@content", SqlDbType.NVarChar).Value = row["buyat_short_deeplink_url"].ToString();
                    cmd2.Parameters.Add("@thecode", SqlDbType.NVarChar).Value = row["product_code"].ToString();

                    string state = row["State"].ToString();

                    //Get Address parameter
                    string street = row["State"].ToString();

                    string locationStr = GetLocation(row["Street"].ToString(), dvStreets);

                    cmd2.Parameters.Add("@state", SqlDbType.NVarChar).Value = state;
                    cmd2.Parameters.Add("@address", SqlDbType.NVarChar).Value = locationStr;
                    cmd2.ExecuteNonQuery();

                }

                #endregion

                StatusPanel.Text += "inserted event and veue;";

                conn.Close();

            }
            catch (Exception ex)
            {
                StatusPanelPanel.Visible = true;

                StatusPanel.Text = ex.ToString();
            }
        }
    }
    protected void PostItEventsByTix(DataRowView row)
    {
        string message = "";
        bool cont = true;
        if (row["VenueID"].ToString().Trim() == "")
            cont = false;

        if (cont)
        {
            HttpCookie cookie = Request.Cookies["BrowserDate"];
            string problem = "";
            try
            {
                StatusPanel.Text += "got inside";
                Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

                SqlCommand cmd;
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
                conn.Open();
                DataView dvVenue = dat.GetDataDV("SELECT * FROM Venues WHERE TixMasterCode=" + row["VenueID"].ToString());

                if (dvVenue.Count > 0)
                {

                    DataView dvEvent = dat.GetDataDV("SELECT * FROM Events WHERE Header= '" +
                        row["product_name"].ToString().Replace("'", "''") + "' AND Venue=" + dvVenue[0]["ID"].ToString());

                    string temporaryID;

                    if (dvEvent.Count == 0)
                    {
                        string email = "";
                        string textEmail = "";

                        //this means there is no pictures or videos
                        DataSet dsEvent = new DataSet();
                        string theCat = "NULL";

                        string command = "";

                        command = "INSERT INTO Events (Owner, [Content], " +
                             "Header, Venue, EventGoersCount, SponsorPresenter, hasSongs, mediaCategory, UserName, "
                         + "ShortDescription, Country, State, Zip, City, StarRating, PostedOn, BuyAtTix)"
                             + " VALUES(@owner, @content, @header, @venue, "
                             + " 0, @sponsor, 0, 0, @userName, @shortDescription"
                         + ", @country, @state, @zip, @city, 0, @dateP, '" + row["buyat_short_deeplink_url"].ToString() + "')";

                        cmd = new SqlCommand(command, conn);
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Add("@dateP", SqlDbType.DateTime).Value = DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"));
                        cmd.Parameters.Add("@content", SqlDbType.NVarChar).Value = row["product_name"].ToString() + " <br/> This events was grabbed from a feed by TicketMaster. As this feed does not provide an end time, all such events are reported as having the end time 1hour after start time. Please check out TicketMaster for the actual end time!";
                        cmd.Parameters.Add("@header", SqlDbType.NVarChar).Value = row["product_name"].ToString();
                        cmd.Parameters.Add("@shortDescription", SqlDbType.NVarChar).Value = row["product_name"].ToString();
                        cmd.Parameters.Add("@userName", SqlDbType.NVarChar).Value = "HippoHappenings";
                        cmd.Parameters.Add("@owner", SqlDbType.Int).Value = DBNull.Value;
                        cmd.Parameters.Add("@sponsor", SqlDbType.NVarChar).Value = DBNull.Value;

                        cmd.Parameters.Add("@venue", SqlDbType.Int).Value = int.Parse(dvVenue[0]["ID"].ToString());

                        cmd.Parameters.Add("@country", SqlDbType.Int).Value = dvVenue[0]["Country"].ToString();
                        cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = dvVenue[0]["State"].ToString();
                        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = dvVenue[0]["City"].ToString();
                        cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = dvVenue[0]["Zip"].ToString();

                        cmd.ExecuteNonQuery();

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

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

                        CreateCategories(temporaryID, row["level1"].ToString());
                    }
                    else
                    {
                        temporaryID = dvEvent[0]["ID"].ToString();
                    }

                    StatusPanel.Text += "inserted event and veue;";

                    string dtime = row["EventDate"].ToString().Replace(" 12:00:00 AM", "") + " " +
                        row["EventTime"].ToString().Replace("12/30/1899", "");

                    message += dtime;
                    DateTime dt = DateTime.Parse(dtime);

                    StatusPanel.Text += ";startime:" + dt.ToString();

                    cmd = new SqlCommand("INSERT INTO Event_Occurance (EventID, DateTimeStart, DateTimeEnd) VALUES(@eventID, @dateStart, @dateEnd)", conn);
                    cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = temporaryID;
                    cmd.Parameters.Add("@dateStart", SqlDbType.DateTime).Value = dt;
                    cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = dt.AddHours(1);
                    cmd.ExecuteNonQuery();

                    conn.Close();

                }

            }
            catch (Exception ex)
            {
                StatusPanelPanel.Visible = true;

                StatusPanel.Text += ex.ToString() + ", dt: " + message;
            }
        }
    }
    protected void PostItEventsByHand(DataRowView row)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        string problem = "";
        try
        {
            if (row["Content"].ToString().Trim() != "" && row["Header"].ToString().Trim() != "")
            {
                StatusPanel.Text += "got inside";
                Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
                string email = "";
                string textEmail = "";
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
                conn.Open();

                //this means there is no pictures or videos

                DataSet dsEvent = new DataSet();
                string theCat = "NULL";

                string command = "";

                command = "INSERT INTO Events (Owner, [Content], " +
                     "Header, Venue, EventGoersCount, SponsorPresenter, hasSongs, mediaCategory, UserName, "
                 + "ShortDescription, Country, State, Zip, City, StarRating, PostedOn)"
                     + " VALUES(@owner, @content, @header, @venue, "
                     + " 0, @sponsor, 0, 0, @userName, @shortDescription"
                 + ", @country, @state, @zip, @city, 0, @dateP)";

                SqlCommand cmd = new SqlCommand(command, conn);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add("@dateP", SqlDbType.DateTime).Value = DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"));
                cmd.Parameters.Add("@content", SqlDbType.NVarChar).Value = row["Content"].ToString();
                cmd.Parameters.Add("@header", SqlDbType.NVarChar).Value = dat.CleanExcelString(row["Header"].ToString());
                cmd.Parameters.Add("@shortDescription", SqlDbType.NVarChar).Value = row["ShortDescription"].ToString();
                cmd.Parameters.Add("@userName", SqlDbType.NVarChar).Value = row["UserName"].ToString();
                cmd.Parameters.Add("@owner", SqlDbType.Int).Value = DBNull.Value;
                cmd.Parameters.Add("@sponsor", SqlDbType.NVarChar).Value = DBNull.Value;

                #region Create/Assign Venue
                string venue = "";
                bool isNewVenue = false;
                int venueID = 0;
                string country = "";
                string state1 = "";

                //User created a new venue. Must save it.
                string city = "";
                string zip = "";
                string state = "";
                bool goNext = true;
                if (row["VenueID"] != null)
                {
                    if (row["VenueID"].ToString().Trim() != "")
                    {
                        venueID = int.Parse(row["VenueID"].ToString());
                        isNewVenue = false;
                        goNext = false;
                        DataView dvA = dat.GetDataDV("SELECT * FROM Venues WHERE ID=" + row["VenueID"].ToString());
                        country = dvA[0]["Country"].ToString();
                        city = dvA[0]["City"].ToString();
                        zip = dvA[0]["Zip"].ToString();
                        state = dvA[0]["State"].ToString();
                    }
                }

                SqlCommand cmd2;
                //SqlCommand cmd2 = new SqlCommand("SELECT * FROM Venues WHERE Name=@name", conn);
                //cmd2.Parameters.Add("@name", SqlDbType.NVarChar).Value = venue;

                //SqlDataAdapter da = new SqlDataAdapter(cmd2);
                //DataSet ds = new DataSet();
                //da.Fill(ds);

                //bool goNext = false;

                //if (ds.Tables.Count > 0)
                //    if (ds.Tables[0].Rows.Count > 0)
                //        cmd.Parameters.Add("@venue", SqlDbType.Int).Value = int.Parse(ds.Tables[0].Rows[0]["ID"].ToString());
                //    else
                //        goNext = true;
                //else
                //    goNext = true;

                if (goNext)
                {
                    cmd2 = new SqlCommand("INSERT INTO Venues (Content, Name, Address, Country, State, City, Zip, " +
                        "MediaCategory, CreatedByUser, Edit, Rating) VALUES (@content, @vName, @address, @country, @state, @city, @zip, 0, @user, 'True', 0)", conn);
                    cmd2.Parameters.Add("@vName", SqlDbType.NVarChar).Value = row["VenueName"].ToString();
                    cmd2.Parameters.Add("@user", SqlDbType.Int).Value = row["UserID"].ToString();
                    cmd2.Parameters.Add("@country", SqlDbType.Int).Value = row["Country"].ToString();
                    cmd2.Parameters.Add("@city", SqlDbType.NVarChar).Value = row["City"].ToString();
                    cmd2.Parameters.Add("@zip", SqlDbType.NVarChar).Value = row["Zip"].ToString();
                    cmd2.Parameters.Add("@content", SqlDbType.NVarChar).Value = row["VenueContent"].ToString();
                    state = row["State"].ToString();

                    string locationStr = "";
                    string apt = "";
                    if (row["AptNumber"].ToString().Trim() != "")
                        apt = row["SuiteApt"].ToString() + " " + row["AptNumber"].ToString();

                    locationStr = row["StreetNumber"].ToString() + ";" + row["StreetName"].ToString().Trim().ToLower()
                        + ";" + row["StreetTitle"].ToString() + ";" + apt;

                    cmd2.Parameters.Add("@state", SqlDbType.NVarChar).Value = state;
                    cmd2.Parameters.Add("@address", SqlDbType.NVarChar).Value = locationStr;
                    cmd2.ExecuteNonQuery();

                    cmd2 = new SqlCommand("SELECT @@IDENTITY AS AID", conn);

                    SqlDataAdapter da1 = new SqlDataAdapter(cmd2);
                    DataSet ds2 = new DataSet();
                    da1.Fill(ds2);

                    venueID = int.Parse(ds2.Tables[0].Rows[0]["AID"].ToString());

                    country = row["Country"].ToString();
                    city = row["City"].ToString();
                    zip = row["Zip"].ToString();
                }

                cmd.Parameters.Add("@venue", SqlDbType.Int).Value = venueID;

                cmd.Parameters.Add("@country", SqlDbType.Int).Value = country;
                cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = state;
                cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = city;
                cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = zip;

                #endregion

                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();

                string temporaryID = ID;

                CreateCategories(temporaryID, row["Categories"].ToString());

                StatusPanel.Text += "inserted event and veue;";

                #region Take Care of Event Occurance

                StatusPanel.Text += ";startime:" + row["StartDateTime"].ToString();

                cmd = new SqlCommand("INSERT INTO Event_Occurance (EventID, DateTimeStart, DateTimeEnd) VALUES(@eventID, @dateStart, @dateEnd)", conn);
                cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = temporaryID;
                cmd.Parameters.Add("@dateStart", SqlDbType.DateTime).Value = row["StartDateTime"].ToString();
                cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = row["EndDateTime"].ToString();
                cmd.ExecuteNonQuery();

                #endregion

                conn.Close();

            }

        }
        catch (Exception ex)
        {
            StatusPanelPanel.Visible = true;

            StatusPanel.Text = ex.ToString();
        }
    }
    /// <summary>
    /// a.	Get all users who have ad searches that are Live and match the criteria
    ///i.	If the ad count ads up to the number in NumAdsInEmail
    ///1.	    Construct the email with those ads
    ///a.	        Big ads are bigger and on the top.
    ///2.	    Send the email
    ///a.	        When email is sent, update the viewed count for the ad in the Ads table. 
    ///b.	        Update the AdStatistics table with the ad and the manner the ad was seen: which will be Email not site view.
    ///3.	        Clear the list of ads in EmailAdList column
    ///ii.	If the ad count is less than NumAdsInEmail, 
    ///1.	    add this ad ID to the EmailAdList column.
    ///2.	    Increment the CountInEmailList column.
    /// </summary>
    /// <param name="adID"></param>
    protected void EmailSavedSearches(string adID, string views)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        int firstCount = 0;
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
        /// a.	Get all users who have ad searches that are Live and match the criteria

        ///i.	If the ad count ads up to the number in NumAdsInEmail
        ///1.	    Construct the email with those ads
        ///a.	        Big ads are bigger and on the top.
        ///2.	    Send the email
        ///a.	        When email is sent, update the viewed count for the ad in the Ads table.
        ///b.	        Update the AdStatistics table with the ad and the manner the ad was seen: which will be Email not site view.
        ///3.	        Clear the list of ads in EmailAdList column
        ///
        int sentAdCount = 0;

        int totalAdCount = int.Parse(views);

        Hashtable notTable = new Hashtable();
        //Send searches that are ready to go

            DataView dvSearches = GetSavedSearchesUsers(ref firstCount, false);

            if (firstCount > 0)
            {
                for (int j = 0; j < dvSearches.Count; j++)
                {
                    //Check if user has see the ad (the ad could be edited)
                    DataView dvAdStats = dat.GetDataDV("SELECT * FROM AdStatistics WHERE AdID=" +
                        adID + " AND UserID=" + dvSearches[j]["UserID"].ToString());
                    if (dvAdStats.Count == 0)
                    {

                        string toEmail = "";
                        ///a.	        When email is sent, update the viewed count for the ad in the Ads table.
                        ///b.	        Update the AdStatistics table with the ad and the manner the ad was seen: which will be Email not site view.
                        ///3.	        Clear the list of ads in EmailAdList column
                        string email = ConstructSearchesEmail(dvSearches[j]["ID"].ToString(), adID, ref toEmail,
                            ref sentAdCount, totalAdCount);

                        if (email != "")
                        {
                            notTable.Add(dvSearches[j]["ID"].ToString(), "1");
                            email = "<table><tr><td>" + email +
                                "</td></tr></table><br/><br/><br/>Have a Hippo Happening Day!<br/><br/>";
                            if (!Request.IsLocal)
                            {
                                dat.SendEmail(System.Configuration.ConfigurationManager.AppSettings["emailemail"].ToString(),
                                    System.Configuration.ConfigurationManager.AppSettings["emailName"].ToString(), toEmail,
                                    email, "Your Saved Search Ads");
                            }
                            if (sentAdCount >= totalAdCount)
                            {
                                break;
                            }
                        }
                    }
                }

                //If we have already reached the total ad count that this user has paid for, notify the user.
                if (sentAdCount >= totalAdCount)
                {
                    if (!Request.IsLocal)
                        dat.SendAdFinishedEmail(adID);
                }
            }
            ///ii.	If the ad count is less than NumAdsInEmail,
            ///1.	    add this ad ID to the EmailAdList column.
            ///2.	    Increment the CountInEmailList column.
            else
            {

            }

        //For the searches that are not ready to go yet, increment their set with this new ad
        DataView dvNotReadySearches = GetSavedSearchesUsers(ref firstCount, true);
        for (int i = 0; i < dvNotReadySearches.Count; i++)
        {
            if (Session["User"].ToString() != dvNotReadySearches[i]["UserID"].ToString())
            {
                //use the notTable hash to determine whether this search has be already updated in this post
                if (!notTable.Contains(dvNotReadySearches[i]["ID"].ToString()))
                {
                    dat.Execute("UPDATE SavedAdSearches SET CountInEmailList = CASE WHEN (CountInEmailList IS NULL) THEN 1 " +
                        "ELSE CountInEmailList + 1 END, EmailAdList = CASE WHEN (EmailAdList IS NULL) THEN ';" + adID +
                        "' ELSE EmailAdList + ';'+ '" +
                        adID + "' END WHERE ID=" + dvNotReadySearches[i]["ID"].ToString());
                }
            }
        }
    }
    protected string ConstructSearchesEmail(string searchID, string adID, ref string toEmail, ref int sentAdCount,
        int totalAdCount)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        int normalAdCount = 0;

        DataSet dsAdsOne = dat.GetData("SELECT * FROM Ads A, Users U WHERE A.User_ID=U.User_ID AND A.Ad_ID=" +
            adID + " ORDER BY A.BigAd DESC");
        DataView dvAdsOne = new DataView(dsAdsOne.Tables[0], "", "", DataViewRowState.CurrentRows);

        DataSet ds = dat.GetData("SELECT * FROM SavedAdSearches WHERE ID=" + searchID);

        DataView dv = new DataView(ds.Tables[0], "", "", DataViewRowState.CurrentRows);

        if (dv[0]["UserID"].ToString() != Session["User"].ToString())
        {
            char[] delim = { ';' };
            string[] tokens = dv[0]["EmailAdList"].ToString().Split(delim);

            string ads = "";
            for (int i = 0; i < tokens.Length; i++)
            {
                if (tokens[i].Trim() != "")
                {
                    if (ads != "")
                        ads += " OR ";
                    else
                        ads = "( ";
                    ads += " A.Ad_ID=" + tokens[i].Trim();
                }
            }

            if (ads != "")
            {
                ads = " AND " + ads + " ) ";
            }

            DataSet dsAds = dat.GetData("SELECT * FROM Ads A, Users U WHERE A.User_ID=U.User_ID " + ads +
                " ORDER BY A.BigAd DESC");
            DataView dvAds = new DataView(dsAds.Tables[0], "", "", DataViewRowState.CurrentRows);

            toEmail = dat.GetData("SELECT * FROM Users WHERE User_ID=" + dv[0]["UserID"].ToString()).Tables[0].Rows[0]["Email"].ToString();

            string email = "";

            email = "Below you will find ads pertaining to one of your saved ad searches. <br/><br/><table cellspacing=\"5\">";

            string categories = "";

            DataSet dsCats = dat.GetData("SELECT * FROM SavedAdSearches_Categories WHERE SearchID=" + searchID);
            DataView dvCats = new DataView(dsCats.Tables[0], "", "", DataViewRowState.CurrentRows);

            for (int n = 0; n < dvCats.Count; n++)
            {
                categories += dvCats[n]["CategoryID"].ToString() + ";";
            }
            DataView dvAdStatistics;
            if (bool.Parse(dvAdsOne[0]["BigAd"].ToString()))
            {
                email += GetEmailString(dvAdsOne[0]["Header"].ToString(), dvAdsOne[0]["FeaturedPicture"].ToString(),
                    dvAdsOne[0]["Ad_ID"].ToString(), dvAdsOne[0]["FeaturedSummary"].ToString(),
                    dvAdsOne[0]["UserName"].ToString(), bool.Parse(dvAdsOne[0]["BigAd"].ToString()), ref normalAdCount);

                ///a.	        When email is sent, update the viewed count for the ad in the Ads table.
                ///BUT ONLY IF THE USER HAS NOT SEEN THIS AD PREVIOUSLY
                ///
                dvAdStatistics =
                    dat.GetDataDV("SELECT * FROM AdStatistics WHERE UserID=" + dv[0]["UserID"].ToString() +
                    " AND AdID=" + dvAdsOne[0]["Ad_ID"].ToString());
                if (dvAdStatistics.Count == 0)
                {
                    dat.Execute("UPDATE Ads SET NumCurrentViews = NumCurrentViews + 1 WHERE Ad_ID=" + dvAdsOne[0]["Ad_ID"].ToString());
                    ///b.	        Update the AdStatistics table with the ad and the manner the ad was seen:
                    /////which will be Email not site view.
                    //[UserID],[Reason],[LocationOnly],[Date],[AdID]

                    string locOnly = "'False'";
                    if (categories.Trim() == "")
                        locOnly = "'True'";
                    dat.Execute("INSERT INTO AdStatistics (UserID, Reason, LocationOnly, Date, AdID, WasEmail) VALUES(" + dv[0]["UserID"].ToString() +
                        ", '" + categories + "', " + locOnly + ", '" + DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToString() + "', " + dvAdsOne[0]["Ad_ID"].ToString() + ", 'True')");

                    //update the ad count for the algorithm
                    sentAdCount++;

                }
            }

            if (ads.Trim() != "")
            {
                for (int j = 0; j < dvAds.Count; j++)
                {
                    email += GetEmailString(dvAds[j]["Header"].ToString(), dvAds[j]["FeaturedPicture"].ToString(),
                        dvAds[j]["Ad_ID"].ToString(), dvAds[j]["FeaturedSummary"].ToString(),
                        dvAds[j]["UserName"].ToString(), bool.Parse(dvAds[j]["BigAd"].ToString()), ref normalAdCount);

                    dvAdStatistics =
                    dat.GetDataDV("SELECT * FROM AdStatistics WHERE UserID=" + dv[0]["UserID"].ToString() +
                    " AND AdID=" + dvAds[j]["Ad_ID"].ToString());
                    if (dvAdStatistics.Count == 0)
                    {
                        ///a.	        When email is sent, update the viewed count for the ad in the Ads table.
                        dat.Execute("UPDATE Ads SET NumCurrentViews = NumCurrentViews + 1 WHERE Ad_ID=" + dvAds[j]["Ad_ID"].ToString());

                        string locOnly = "'False'";
                        if (categories.Trim() == "")
                            locOnly = "'True'";

                        ///b.	        Update the AdStatistics table with the ad and the manner the ad was seen:
                        /////which will be Email not site view.
                        //[UserID],[Reason],[LocationOnly],[Date],[AdID]
                        dat.Execute("INSERT INTO AdStatistics (UserID, Reason, LocationOnly, Date, AdID, WasEmail) VALUES(" + dv[0]["UserID"].ToString() +
                            ", '" + categories + "', " + locOnly + ", '" + DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToString() + "', " +
                            dvAds[j]["Ad_ID"].ToString() + ", 'True')");
                    }
                }
            }

            if (!bool.Parse(dvAdsOne[0]["BigAd"].ToString()))
            {
                email += GetEmailString(dvAdsOne[0]["Header"].ToString(), dvAdsOne[0]["FeaturedPicture"].ToString(),
                    dvAdsOne[0]["Ad_ID"].ToString(), dvAdsOne[0]["FeaturedSummary"].ToString(),
                    dvAdsOne[0]["UserName"].ToString(), bool.Parse(dvAdsOne[0]["BigAd"].ToString()), ref normalAdCount);

                //Only when this ad is not found in adstatistics of the user do we increment the count
                dvAdStatistics =
                    dat.GetDataDV("SELECT * FROM AdStatistics WHERE UserID=" + dv[0]["UserID"].ToString() +
                    " AND AdID=" + dvAdsOne[0]["Ad_ID"].ToString());

                if (dvAdStatistics.Count == 0)
                {
                    ///a.	        When email is sent, update the viewed count for the ad in the Ads table.
                    dat.Execute("UPDATE Ads SET NumCurrentViews = NumCurrentViews + 1 WHERE Ad_ID=" + dvAdsOne[0]["Ad_ID"].ToString());

                    string locOnly = "'False'";
                    if (categories.Trim() == "")
                        locOnly = "'True'";
                    ///b.	        Update the AdStatistics table with the ad and the manner the ad was seen:
                    /////which will be Email not site view.
                    //[UserID],[Reason],[LocationOnly],[Date],[AdID]
                    dat.Execute("INSERT INTO AdStatistics (UserID, Reason, LocationOnly, Date, AdID, WasEmail) VALUES(" + dv[0]["UserID"].ToString() +
                        ", '" + categories + "', " + locOnly + ", '" +
                        DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToString() +
                        "', " + dvAdsOne[0]["Ad_ID"].ToString() + ", 'True')");

                    //update the ad count for the algorithm
                    sentAdCount++;
                }
            }

            email += "</table>";

            ///3.	        Clear the list of ads in EmailAdList column

            dat.Execute("UPDATE SavedAdSearches SET EmailAdList='', CountInEmailList=0 WHERE ID=" + searchID);

            return email;
        }
        else
        {
            return "";
        }
    }
    //protected void GetAvailableUsers(DateTime startDate, bool isBig)
    //{
    //    CategoryDaysPanel.Controls.Clear();
    //    UpdatePanel Up = new UpdatePanel();
    //    Up.ChildrenAsTriggers = false;
    //    Up.ID = "Up";
    //    Up.UpdateMode = UpdatePanelUpdateMode.Conditional;
    //    Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
    //    string txtLocation = CountryDropDown.SelectedItem.Text;
    //    string state = "";
    //    if (StateDropDownPanel.Visible)
    //        state = StateDropDown.SelectedItem.Text;
    //    else
    //        state = StateTextBox.THE_TEXT;
    //    int firstDayCount = 0;
    //    int secDayCount = 0;
    //    int thirdDayCount = 0;
    //    int fourthDayCount = 0;
    //    int firstDayCountLoc = 0;
    //    int secDayCountLoc = 0;
    //    int thirdDayCountLoc = 0;
    //    int fourthDayCountLoc = 0;
    //    TotalUsers.Text = firstDayCount.ToString();
    //    string city = "";
    //    if (CityTextBox.Text.Trim() != "")
    //    {
    //        city = CityTextBox.Text.Trim();
    //    }
    //    else
    //    {
    //        city = null;
    //    }
    //    bool isNoUsers = false;
    //    string categories = "";
    //    dat.returnCategoryIDString(CategoryTree, ref categories);
    //    dat.returnCategoryIDString(RadTreeView1, ref categories);
    //    dat.returnCategoryIDString(RadTreeView2, ref categories);
    //    dat.returnCategoryIDString(RadTreeView3, ref categories);
    //    dat.CalculateUsersAdCapacity(city, state, CountryDropDown.SelectedItem.Value, categories, startDate,
    //        ref firstDayCount, ref secDayCount, ref thirdDayCount, ref fourthDayCount, ref isNoUsers, isBig, false);
    //    dat.CalculateUsersAdCapacity(city, state, CountryDropDown.SelectedItem.Value, categories, startDate,
    //        ref firstDayCountLoc, ref secDayCountLoc, ref thirdDayCountLoc, ref fourthDayCountLoc, ref isNoUsers,
    //        isBig, true);
    //    System.Drawing.Color green = System.Drawing.Color.FromArgb(98, 142, 2);
    //    string startDateReal = "";
    //    if (Session["SelectedStartDate"] == null)
    //        startDateReal = ((DateTime)StartDateTimePicker.DbSelectedDate).ToShortDateString();
    //    else
    //        startDateReal = Session["SelectedStartDate"].ToString();
    //    Literal lab = new Literal();
    //    lab.ID = "dateLiteral";
    //    lab.Text = "<div style=\"clear: both; float: right;\"><label>Selected Start Date: </label><span "+
    //        "class=\"AddGreenLinkBig\">" + startDateReal + "</span></div><div style=\"clear: both;\">";
    //    Panel topPanel = new Panel();
    //    topPanel.Width = 590;
    //    LinkButton link1 = new LinkButton();
    //    if (startDate <= DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).Date)
    //    {
    //        link1.Enabled = false;
    //        link1.CssClass = "AddLinkNoPaddingDisabled";
    //    }
    //    else
    //    {
    //        link1.Enabled = true;
    //        link1.CssClass = "AddLinkNoPadding";
    //    }
    //    link1.Text = "Previous 4 Days";
    //    link1.Style.Add("float", "left");
    //    link1.Click += new EventHandler(prev4Click);
    //    link1.ID = "prevLink";
    //    LinkButton link = new LinkButton();
    //    link.Text = "Next 4 Days";
    //    link.ID = "nextLink";
    //    link.CssClass = "AddLinkNoPadding";
    //    link.Style.Add("float", "right");
    //    link.Click += new EventHandler(next4Click);
    //    Literal lit2 = new Literal();
    //    lit2.Text = "</div>";
    //    topPanel.Controls.Add(lab);
    //    topPanel.Controls.Add(link1);
    //    topPanel.Controls.Add(link);
    //    topPanel.Controls.Add(lit2);
    //    Literal lit = new Literal();
    //    lit.Text = "<br/>";
    //    Up.ContentTemplateContainer.Controls.Add(topPanel);
    //    Up.ContentTemplateContainer.Controls.Add(lit);
    //    //Draw the panel
    //    Panel panelDay1 = new Panel();
    //    Label label1 = new Label();
    //    label1.Text = (startDate).Date.ToShortDateString() + "<br/>";
    //    Label label12 = new Label();
    //    label1.CssClass = "NumLabel";
    //    label12.CssClass = "NumLabel";
    //    if (startDate < DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).Date)
    //    {
    //        panelDay1.Enabled = false;
    //        label12.Text = "0 Users in Categories<br/>" +
    //            "0 Users in Location <br/>";
    //    }
    //    else
    //    {
    //        label12.Text = (firstDayCount).ToString() + " Users in Categories<br/>" +
    //            firstDayCountLoc.ToString() + " Users in Location <br/>";
    //    }
    //    Button button1 = new Button();
    //    button1.Text = "Select date";
    //    button1.ID = "selectDate1";
    //    button1.Click += new EventHandler(SelectDate);
    //    button1.CommandArgument = (startDate).Date.ToShortDateString();
    //    panelDay1.Height = 100;
    //    panelDay1.BorderColor = green;
    //    panelDay1.BorderStyle = BorderStyle.Solid;
    //    panelDay1.BorderWidth = 2;
    //    panelDay1.Style.Add("float", "left");
    //    panelDay1.Style.Add("padding", "5px");
    //    panelDay1.Style.Add("margin", "5px");
    //    panelDay1.Controls.Add(label1);
    //    panelDay1.Controls.Add(label12);
    //    panelDay1.Controls.Add(button1);
    //    Up.ContentTemplateContainer.Controls.Add(panelDay1);
    //    Panel panelDay2 = new Panel();
    //    Label label2 = new Label();
    //    label2.Text = (startDate).AddDays(double.Parse("1.00")).ToShortDateString() + "<br/>";
    //    Label label22 = new Label();
    //    if ((startDate).AddDays(double.Parse("1.00")) < DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).Date)
    //    {
    //        panelDay2.Enabled = false;
    //        label22.Text = "0 Users in Categories<br/>" +
    //            "0 Users in Location <br/>";
    //    }
    //    else
    //    {
    //        label22.Text = secDayCount.ToString() + " Users in Categories<br/>" +
    //            secDayCountLoc.ToString() + " Users in Location <br/>";
    //    }
    //    label2.CssClass = "NumLabel";
    //    label22.CssClass = "NumLabel";
    //    Button button2 = new Button();
    //    button2.Text = "Select date";
    //    button2.ID = "selectDate2";
    //    button2.Click += new EventHandler(SelectDate);
    //    button2.CommandArgument = (startDate).AddDays(double.Parse("1.00")).ToShortDateString();
    //    panelDay2.Height = 100;
    //    panelDay2.BorderColor = green;
    //    panelDay2.BorderStyle = BorderStyle.Solid;
    //    panelDay2.BorderWidth = 2;
    //    panelDay2.Style.Add("float", "left");
    //    panelDay2.Style.Add("padding", "5px");
    //    panelDay2.Style.Add("margin", "5px");
    //    panelDay2.Controls.Add(label2);
    //    panelDay2.Controls.Add(label22);
    //    panelDay2.Controls.Add(button2);
    //    Up.ContentTemplateContainer.Controls.Add(panelDay2);
    //    Panel panelDay3 = new Panel();
    //    Label label3 = new Label();
    //    label3.Text = (startDate).AddDays(double.Parse("2.00")).ToShortDateString() + "<br/>";
    //    Label label32 = new Label();
    //    if ((startDate).AddDays(double.Parse("2.00")) < DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).Date)
    //    {
    //        panelDay3.Enabled = false;
    //        label32.Text = "0 Users in Categories<br/>" +
    //           "0 Users in Location <br/>";
    //    }
    //    else
    //    {
    //        label32.Text = secDayCount.ToString() + " Users in Categories<br/>" +
    //            thirdDayCountLoc.ToString() + " Users in Location <br/>";
    //    }
    //    label3.CssClass = "NumLabel";
    //    label32.CssClass = "NumLabel";
    //    Button button3 = new Button();
    //    button3.Text = "Select date";
    //    button3.ID = "selectDate3";
    //    button3.Click += new EventHandler(SelectDate);
    //    button3.CommandArgument = (startDate).AddDays(double.Parse("2.00")).ToShortDateString();
    //    panelDay3.Height = 100;
    //    panelDay3.BorderColor = green;
    //    panelDay3.BorderStyle = BorderStyle.Solid;
    //    panelDay3.BorderWidth = 2;
    //    panelDay3.Style.Add("float", "left");
    //    panelDay3.Style.Add("padding", "5px");
    //    panelDay3.Style.Add("margin", "5px");
    //    panelDay3.Controls.Add(label3);
    //    panelDay3.Controls.Add(label32);
    //    panelDay3.Controls.Add(button3);
    //    Up.ContentTemplateContainer.Controls.Add(panelDay3);
    //    Panel panelDay4 = new Panel();
    //    Label label4 = new Label();
    //    label4.Text = (startDate).AddDays(double.Parse("3.00")).ToShortDateString() + "<br/>";
    //    Label label42 = new Label();
    //    if ((startDate).AddDays(double.Parse("3.00")) < DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).Date)
    //    {
    //        panelDay4.Enabled = false;
    //        label42.Text = "0 Users in Categories<br/>" +
    //            "0 Users in Location <br/>";
    //    }
    //    else
    //    {
    //        label42.Text = secDayCount.ToString() + " Users in Categories<br/>" +
    //            fourthDayCountLoc.ToString() + " Users in Location <br/>";
    //    }
    //    label4.CssClass = "NumLabel";
    //    label42.CssClass = "NumLabel";
    //    Button button4 = new Button();
    //    button4.Text = "Select date";
    //    button4.ID = "selectDate4";
    //    button4.Click += new EventHandler(SelectDate);
    //    button4.CommandArgument = (startDate).AddDays(double.Parse("3.00")).ToShortDateString();
    //    panelDay4.Height = 100;
    //    panelDay4.BorderColor = green;
    //    panelDay4.BorderStyle = BorderStyle.Solid;
    //    panelDay4.BorderWidth = 2;
    //    panelDay4.Style.Add("float", "left");
    //    panelDay4.Style.Add("padding", "5px");
    //    panelDay4.Style.Add("margin", "5px");
    //    panelDay4.Controls.Add(label4);
    //    panelDay4.Controls.Add(label42);
    //    panelDay4.Controls.Add(button4);
    //    Up.ContentTemplateContainer.Controls.Add(panelDay4);
    //    AsyncPostBackTrigger apt = new AsyncPostBackTrigger();
    //    apt.ControlID = link1.ClientID;
    //    apt.EventName = "Click";
    //    Up.Triggers.Add(apt);
    //    AsyncPostBackTrigger apt1 = new AsyncPostBackTrigger();
    //    apt1.ControlID = button1.ClientID;
    //    apt1.EventName = "Click";
    //    Up.Triggers.Add(apt1);
    //    AsyncPostBackTrigger apt2 = new AsyncPostBackTrigger();
    //    apt2.ControlID = link.ClientID;
    //    apt2.EventName = "Click";
    //    Up.Triggers.Add(apt2);
    //    AsyncPostBackTrigger apt3 = new AsyncPostBackTrigger();
    //    apt3.ControlID = button2.ClientID;
    //    apt3.EventName = "Click";
    //    Up.Triggers.Add(apt3);
    //    AsyncPostBackTrigger apt4 = new AsyncPostBackTrigger();
    //    apt4.ControlID = button3.ClientID;
    //    apt4.EventName = "Click";
    //    Up.Triggers.Add(apt4);
    //    AsyncPostBackTrigger apt5 = new AsyncPostBackTrigger();
    //    apt5.ControlID = button4.ClientID;
    //    apt5.EventName = "Click";
    //    Up.Triggers.Add(apt5);
    //    AsyncPostBackTrigger apt6 = new AsyncPostBackTrigger();
    //    apt6.ControlID = AdPlacementList.UniqueID;
    //    apt6.EventName = "SelectedIndexChanged";
    //    Up.Triggers.Add(apt6);
    //    Up.Update();
    //    CategoryDaysPanel.Controls.Add(Up);
    //}
    //protected void SelectDate(object sender, EventArgs e)
    //{
    //    Button b = (Button)sender;
    //    string startDateReal = b.CommandArgument;
    //    Session["SelectedStartDate"] = startDateReal;
    //    Literal lab = (Literal)CategoryDaysPanel.FindControl("dateLiteral");
    //    lab.Text = "<div style=\"clear: both; float: right;\"><label>Selected Start Date: </label><span " +
    //        "class=\"AddGreenLinkBig\">" + startDateReal + "</span></div><div style=\"clear: both;\">";
    //    UpdatePanel up = (UpdatePanel)CategoryDaysPanel.FindControl("Up");
    //    up.Update();
    //}
    //protected void next4Click(object sender, EventArgs e)
    //{
    //    //CategoryDaysPanel.Controls.Clear();
    //    Session["UserAvailableDate"] = ((DateTime)Session["UserAvailableDate"]).AddDays(4);
    //    bool isBig = false;
    //    if (AdPlacementList.SelectedValue == "0.04")
    //        isBig = true;
    //    GetAvailableUsers((DateTime)Session["UserAvailableDate"], isBig);
    //}
    //protected void prev4Click(object sender, EventArgs e)
    //{
    //    CategoryDaysPanel.Controls.Clear();
    //    Session["UserAvailableDate"] = ((DateTime)Session["UserAvailableDate"]).AddDays(-4);
    //    bool isBig = false;
    //    if (AdPlacementList.SelectedValue == "0.04")
    //        isBig = true;
    //    GetAvailableUsers((DateTime)Session["UserAvailableDate"], isBig);
    //}
    private void FillLiteral()
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        if (bool.Parse(isFeatured.Text))
        {
            FeaturedWeWouldPanel.Visible = true;
            bool isBig = false;
            if (AdPlacementList.SelectedValue == "0.04")
                isBig = true;
            FeaturedPreviewPanel.Visible = true;
            int integer = 2;
            string username = dat.GetDataDV("select * from Users where user_id=" + Session["User"].ToString())[0]["UserName"].ToString();
            string email = "";
            if (AdPictureCheckList.Items.Count == 0 || !AdMediaPanel.Visible)
                email = GetEmailString(AdNameTextBox.THE_TEXT, null,
                 null, SummaryTextBox.InnerHtml, username, isBig, ref integer);
            else
                email = GetEmailString(AdNameTextBox.THE_TEXT, AdPictureCheckList.Items[0].Value,
                 null, SummaryTextBox.InnerHtml, username, isBig, ref integer);

            if (!isBig)
                email += "</tr>";

            email = "<table>" + email + "</table>";
            FeaturedPreviewLiteral.Text = email;
        }
        else
        {
            FeaturedWeWouldPanel.Visible = false;
        }

        EventPanel.Visible = true;
        ShowHeaderName.Text = AdNameTextBox.THE_TEXT;
        ShowDescription.Text = dat.BreakUpString(DescriptionTextBox.Content, 60);

        Rotator1.Items.Clear();
        char[] delim = { '\\' };
        string[] fileArray;

        string[] finalFileArray = new string[PictureCheckList.Items.Count];

        if (System.IO.Directory.Exists(MapPath(".") + "\\UserFiles\\" +
             Session["UserName"].ToString() + "\\AdSlider\\"))
        {
            fileArray = System.IO.Directory.GetFiles(MapPath(".") + "\\UserFiles\\" +
                 Session["UserName"].ToString() + "\\AdSlider\\");

        }

        //for (int i = 0; i < PictureCheckList.Items.Count; i++)
        //{
        //    finalFileArray[i] = "http://" + Request.Url.Authority + "/HippoHappenings/UserFiles/" +
        //        Session["UserName"].ToString() + "/Slider/" + PictureCheckList.Items[i].Value;
        //}
        char[] delim2 = { '.' };
        for (int i = 0; i < PictureCheckList.Items.Count; i++)
        {
            Literal literal4 = new Literal();
            string[] tokens = PictureCheckList.Items[i].Value.ToString().Split(delim2);
            if (tokens.Length >= 2)
            {
                if (tokens[1].ToUpper() == "JPG" || tokens[1].ToUpper() == "JPEG" || tokens[1].ToUpper() == "GIF")
                {
                    System.Drawing.Image image = System.Drawing.Image.FromFile(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider\\" + PictureCheckList.Items[i].Value.ToString());

                    int width = 410;
                    int height = 250;

                    int newHeight = image.Height;
                    int newIntWidth = image.Width;

                    ////if image height is less than resize height
                    //if (height >= image.Height)
                    //{
                    //    //leave the height as is
                    //    newHeight = image.Height;

                    //    if (width >= image.Width)
                    //    {
                    //        newIntWidth = image.Width;
                    //    }
                    //    else
                    //    {
                    //        newIntWidth = width;

                    //        double theDivider = double.Parse(image.Width.ToString()) / double.Parse(newIntWidth.ToString());
                    //        double newDoubleHeight = double.Parse(newHeight.ToString());
                    //        newDoubleHeight = double.Parse(height.ToString()) / theDivider;
                    //        newHeight = (int)newDoubleHeight;
                    //    }
                    //}
                    ////if image height is greater than resize height...resize it
                    //else
                    //{
                    //    //make height equal to the requested height.
                    //    newHeight = height;

                    //    //get the ratio of the new height/original height and apply that to the width
                    //    double theDivider = double.Parse(image.Height.ToString()) / double.Parse(newHeight.ToString());
                    //    double newDoubleWidth = double.Parse(newIntWidth.ToString());
                    //    newDoubleWidth = double.Parse(image.Width.ToString()) / theDivider;
                    //    newIntWidth = (int)newDoubleWidth;

                    //    //if the resized width is still to big
                    //    if (newIntWidth > width)
                    //    {
                    //        //make it equal to the requested width
                    //        newIntWidth = width;

                    //        //get the ratio of old/new width and apply it to the already resized height
                    //        theDivider = double.Parse(image.Width.ToString()) / double.Parse(newIntWidth.ToString());
                    //        double newDoubleHeight = double.Parse(newHeight.ToString());
                    //        newDoubleHeight = double.Parse(image.Height.ToString()) / theDivider;
                    //        newHeight = (int)newDoubleHeight;
                    //    }
                    //}

                    literal4.Text = "<div style=\"width: 410px; height: 250px;background-color: black;\"><img style=\"cursor: pointer; margin-left: " + ((410 - newIntWidth) / 2).ToString() + "px; margin-top: " + ((250 - newHeight) / 2).ToString() + "px;\" height=\"" + newHeight + "px\" width=\"" + newIntWidth + "px\" src=\""
                        + "UserFiles/" + Session["UserName"].ToString() + "/AdSlider/" + PictureCheckList.Items[i].Value.ToString() + "\" /></div>";

                }
                else if (tokens[1].ToUpper() == "WMV")
                {
                    literal4.Text = "<object><param  name=\"wmode\" value=\"opaque\" ></param><embed wmode=\"opaque\" height=\"250px\" width=\"410px\" src=\""
                        + "UserFiles/" + Session["UserName"].ToString() + "/AdSlider/" + PictureCheckList.Items[i].Value.ToString() +
                        "\" /></object>";
                }
            }
            else
            {
                literal4.Text = "<div style=\"float:left;\"><object width=\"410\" height=\"250\"><param  name=\"wmode\" value=\"opaque\" ></param><param name=\"movie\" value=\"http://www.youtube.com/v/" + PictureCheckList.Items[i].Value.ToString() + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed wmode=\"opaque\" src=\"http://www.youtube.com/v/" + PictureCheckList.Items[i].Value.ToString() + "\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"410\" height=\"250\"></embed></object></div>";
            }

            Telerik.Web.UI.RadRotatorItem r4 = new Telerik.Web.UI.RadRotatorItem();
            r4.Controls.Add(literal4);
            Rotator1.Items.Add(r4);
        }

        if (Rotator1.Items.Count == 0)
            RotatorPanel.Visible = false;
        else
            RotatorPanel.Visible = true;

        if (Rotator1.Items.Count == 1)
            RotatorPanel.CssClass = "HiddeButtons";
        else
            RotatorPanel.CssClass = "";

        //if (MainAttractionCheck.Checked)
        //{
        //    if (MainAttractionRadioList.SelectedValue == "0")
        //    {
        //        Rotator1.Items.Clear();
        //        RotatorPanel.Visible = false;
        //        if (VideoPictureRadioList.SelectedValue == "0")
        //        {
        //            if (PictureCheckList.Items.Count != 0)
        //                ShowVideoPictureLiteral.Text = "<img style=\"float: left; padding-right: 10px; padding-top: 9px;\" height=\"250px\" width=\"440px\" src=\"UserFiles/" + PictureCheckList.Items[0].Value + "\" />";
        //        }
        //        else
        //        {
        //            if (VideoRadioList.SelectedValue == "0")
        //            {
        //                //ShowVideoPictureLiteral.Text = "<div style=\"float:left; padding-top: 9px; padding-right: 10px;\"><embed  height=\"250px\" width=\"440px\" src=\"UserFiles/" + VideoCheckList.Items[0].Text + "\" /></div>";
        //                ShowVideoPictureLiteral.Text = "<div style=\"float:left; padding-top: 9px; padding-right: 10px;\"><object width=\"440\" height=\"250\"><param name=\"movie\" value=\"UserFiles/" + VideoCheckList.Items[0].Text + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"UserFiles/" + VideoCheckList.Items[0].Text + "\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"440\" height=\"250\"></embed></object></div>";
        //            }
        //            else
        //                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/" + YouTubeTextBox.Text + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/" + YouTubeTextBox.Text + "\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"440\" height=\"250\"></embed></object></div>";
        //        }
        //    }
        //    else
        //    {
        //        ShowVideoPictureLiteral.Text = "";
        //        if (SliderCheckList.Items.Count > 0)
        //        {
        //            char[] delim = { '\\' };
        //            string[] fileArray = System.IO.Directory.GetFiles(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider\\");

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

        //            for (int i = 0; i < SliderCheckList.Items.Count; i++)
        //            {
        //                finalFileArray[i] = "http://" + Request.Url.Authority + "/HippoHappenings/UserFiles/" +
        //                     Session["UserName"].ToString() + "/AdSlider/" + SliderCheckList.Items[i].Value;
        //            }

        //            Rotator1.DataSource = finalFileArray;
        //            Rotator1.DataBind();
        //            RotatorPanel.Visible = true;
        //        }
        //    }
        //}
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlLink lk = new HtmlLink();
        HtmlHead head = (HtmlHead)Page.Header;
        lk.Attributes.Add("rel", "canonical");
        lk.Href = "http://hippohappenings.com/EnterVenue.aspx";
        head.Controls.AddAt(0, lk);

        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", ":")));
        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = Context.Request.Cookies[cookieName];

        FormsAuthenticationTicket authTicket = null;

        ImageButton5.PostBackUrl = Request.Url.AbsoluteUri;

        Button button = (Button)dat.FindControlRecursive(this, "Button2");
        button.CssClass = "NavBarImageAddVenueSelected";

        DataView dv = dat.GetDataDV("SELECT * FROM TermsAndConditions");
        Literal lit1 = new Literal();
        lit1.Text = dv[0]["Content"].ToString();
        TACTextBox.Controls.Add(lit1);

        if (!IsPostBack)
        {

            Session.Remove("CategoriesSet");
            Session["CategoriesSet"] = null;

            CountryDropDown.SelectedValue = "223";
            DataSet dsCountries = dat.GetData("SELECT * FROM State WHERE country_id=223");

            StateDropDown.DataSource = dsCountries;
            StateDropDown.DataTextField = "state_2_code";
            StateDropDown.DataValueField = "state_id";
            StateDropDown.DataBind();
            StateDropDownPanel.Visible = true;
            StateTextBoxPanel.Visible = false;
        }

        try
        {
            Session["RedirectTo"] = Request.Url.AbsoluteUri;

            if (Session["User"] != null)
            {

                //ASP.controls_ads_ascx Ads1 = new ASP.controls_ads_ascx();
                //Ads1.DATA_SET = dat.RetrieveAds(Session["User"].ToString(), false);
                //Ads1.MAIN_AD_DATA_SET = dat.RetrieveMainAds(Session["User"].ToString());
                //Ads1.Controls.Add(Ads1);
                BigEventPanel.Visible = true;
                LoggedOutPanel.Visible = false;
                LoadControls();

                if (!IsPostBack)
                {
                    if (Request.QueryString["ID"] != null)
                    {

                        fillVenue();

                    }
                }

            }
            else
            {
                WelcomeLabel.Text = "On Hippo Happenings, the users have all the power to post event, ads and venues alike. In order to do so, and for us to maintain clean and manageable content,  "
                    + " we require that you <a class=\"AddLink\" href=\"Register.aspx\">create an account</a> with us. <a class=\"AddLink\" href=\"UserLogin.aspx\">Log in</a> if you have an account already. " +
                    "Having an account with us will allow you to do many other things as well. You'll will be able to add events to your calendar, communicate with others going to events, add your friends, filter content based on your preferences, " +
                    " feature your ads thoughout the site and much more. <br/><br/>So let's go <a class=\"AddLink\" style=\"font-size: 16px;\" href=\"Register.aspx\">Register!</a>";

                BigEventPanel.Visible = false;
                LoggedOutPanel.Visible = true;

            }
        }
        catch (Exception ex)
        {
            ErrorLabel.Text = ex.ToString();
            LoggedOutPanel.Visible = true;
            BigEventPanel.Visible = false;
        }
    }
    protected void fillVenue()
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        //If there is no owner, the venue is up for grabs.
        DataSet dsVenue = dat.GetData("SELECT * FROM Venues WHERE ID=" + Request.QueryString["ID"].ToString());

        bool ownerUpForGrabs = false;
        bool isOwner = EnableOwnerPanel(ref ownerUpForGrabs);

        if (isOwner || ownerUpForGrabs)
        {
            PictureNixItButton.Visible = true;
        }

        if (dsVenue.Tables.Count > 0)
            if (dsVenue.Tables[0].Rows.Count > 0)
            {
                TitleLabel.Text = "You are submitting changes for venue '" + dsVenue.Tables[0].Rows[0]["Name"].ToString() +
                    "'";
                VenueNameTextBox.THE_TEXT = dsVenue.Tables[0].Rows[0]["Name"].ToString();
                PhoneTextBox.Text = dsVenue.Tables[0].Rows[0]["Phone"].ToString();
                EmailTextBox.Text = dsVenue.Tables[0].Rows[0]["Email"].ToString();
                WebSiteTextBox.Text = dsVenue.Tables[0].Rows[0]["Web"].ToString();
                DescriptionTextBox.Content = dsVenue.Tables[0].Rows[0]["Content"].ToString();
                ZipTextBox.Text = dsVenue.Tables[0].Rows[0]["Zip"].ToString();
                CityTextBox.Text = dsVenue.Tables[0].Rows[0]["City"].ToString();
                DataSet dsCountries = dat.GetData("SELECT * FROM State WHERE country_id=" + dsVenue.Tables[0].Rows[0]["Country"].ToString());
                CountryDropDown.SelectedValue = dsVenue.Tables[0].Rows[0]["Country"].ToString();
                bool showStateText = false;
                if (dsCountries.Tables.Count > 0)
                    if (dsCountries.Tables[0].Rows.Count > 0)
                    {
                        StateDropDown.DataSource = dsCountries;
                        StateDropDown.DataTextField = "state_2_code";
                        StateDropDown.DataValueField = "state_id";
                        StateDropDown.DataBind();
                        StateDropDown.SelectedValue = StateDropDown.Items.FindByText(dsVenue.Tables[0].Rows[0]["State"].ToString()).Value;
                        StateDropDownPanel.Visible = true;
                        StateTextBoxPanel.Visible = false;
                    }
                    else
                        showStateText = true;
                else
                    showStateText = true;

                if (showStateText)
                {
                    StateTextBoxPanel.Visible = true;
                    StateDropDownPanel.Visible = false;
                    StateTextBox.THE_TEXT = dsVenue.Tables[0].Rows[0]["State"].ToString();
                }
                char[] delimB = { ';' };
                if (dsVenue.Tables[0].Rows[0]["Country"].ToString() == "223")
                {
                    USPanel.Visible = true;
                    InternationalPanel.Visible = false;
                    string str = dsVenue.Tables[0].Rows[0]["Address"].ToString();

                    string[] atokens = str.Split(delimB);

                    StreetNumberTextBox.Text = atokens[0];
                    try
                    {
                        string temp = atokens[1][0].ToString().ToUpper() + atokens[1].Substring(1, atokens[1].Length - 1);
                        StreetNameTextBox.Text = temp;
                        StreetDropDown.Items.FindByText(atokens[2]).Selected = true;
                        AptNumberTextBox.Text = atokens[3];
                        if (atokens[3].Contains("Suite"))
                        {
                            AptNumberTextBox.Text = AptNumberTextBox.Text.Replace("Suite ", "");
                            AptDropDown.Items.FindByValue("1").Selected = true;
                        }
                        else
                        {
                            AptNumberTextBox.Text = AptNumberTextBox.Text.Replace("Apt ", "");
                            AptDropDown.Items.FindByValue("2").Selected = true;
                        }
                    }
                    catch (Exception ex)
                    {

                    }

                }
                else
                {
                    string[] atokensI = dsVenue.Tables[0].Rows[0]["Address"].ToString().Split(delimB);
                    LocationTextBox.Text = atokensI[0];
                    if (atokensI.Length > 1)
                    {
                        if (atokensI[1].Trim() != "")
                        {
                            AptNumberTextBox.Text = atokensI[1];
                            if (atokensI[1].Contains("Suite"))
                            {
                                AptNumberTextBox.Text = AptNumberTextBox.Text.Replace("Suite ", "");
                                AptDropDown.Items.FindByValue("1").Selected = true;
                            }
                            else
                            {
                                AptNumberTextBox.Text = AptNumberTextBox.Text.Replace("Apt ", "");
                                AptDropDown.Items.FindByValue("2").Selected = true;
                            }
                        }
                    }
                    USPanel.Visible = false;
                    InternationalPanel.Visible = true;
                }

                //string mediaCategory = dsVenue.Tables[0].Rows[0]["mediaCategory"].ToString();
                string youtube = dsVenue.Tables[0].Rows[0]["YouTubeVideo"].ToString();
                char[] delim = { '\\' };
                char[] delim4 = { ';' };
                string[] youtokens = youtube.Split(delim4);
                if (youtokens.Length > 0)
                {
                    MainAttractionCheck.Checked = true;
                    MainAttractionPanel.Enabled = true;
                    MainAttractionPanel.Visible = true;

                    for (int i = 0; i < youtokens.Length; i++)
                    {
                        if (youtokens[i].Trim() != "")
                        {
                            ListItem newListItem = new ListItem("You Tube ID: " + youtokens[i], youtokens[i]);
                            if (isOwner)
                            {
                                newListItem.Enabled = true;
                            }
                            else
                            {
                                newListItem.Enabled = false;
                            }
                            PictureCheckList.Items.Add(newListItem);
                        }
                    }
                }
                if (System.IO.Directory.Exists(MapPath(".") + "\\VenueFiles\\" + Request.QueryString["ID"].ToString() +
                        "\\Slider\\"))
                {
                    string[] fileArray = System.IO.Directory.GetFiles(MapPath(".") + "\\VenueFiles\\" + Request.QueryString["ID"].ToString() +
                        "\\Slider\\");
                    if (fileArray.Length > 0)
                    {
                        MainAttractionCheck.Checked = true;
                        MainAttractionPanel.Enabled = true;
                        MainAttractionPanel.Visible = true;

                        for (int i = 0; i < fileArray.Length; i++)
                        {
                            string[] fileTokens = fileArray[i].Split(delim);
                            string nameFile = fileTokens[fileTokens.Length - 1];

                            DataView dvV = dat.GetDataDV("SELECT * FROM Venue_Slider_Mapping WHERE PictureName='" + nameFile + "' AND VenueID=" + Request.QueryString["ID"].ToString());
                            if (dvV.Count > 0)
                            {
                                ListItem newListItem = new ListItem(dvV[0]["RealPictureName"].ToString(), nameFile);
                                if (isOwner)
                                {
                                    newListItem.Enabled = true;
                                }
                                else
                                {
                                    newListItem.Enabled = false;
                                }
                                PictureCheckList.Items.Add(newListItem);
                            }
                        }
                    }
                }

            }
    }
    protected void fillAd(string ID, bool isedit)
    {
        try
        {
            bool iscopy = true;
            if (Request.QueryString["copy"] == null)
                iscopy = false;
            else if (!bool.Parse(Request.QueryString["copy"].ToString()))
                iscopy = false;

            HttpCookie cookie = Request.Cookies["BrowserDate"];
            Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
            DataSet dsEvent = dat.GetData("SELECT * FROM Ads WHERE Ad_ID=" + ID);
            DataSet dsCalendar = dat.GetData("SELECT * FROM Ad_Calendar WHERE AdID=" + ID);
            AdNameTextBox.THE_TEXT = dsEvent.Tables[0].Rows[0]["Header"].ToString();
            nameLabel.Text = "You are submitting changes for Ad: " + dsEvent.Tables[0].Rows[0]["Header"].ToString(); ;
            nameLabel.Visible = false;
            //Session["EffectiveUserName"] = Session["UserName"].ToString();

            DataSet dsCountry = dat.GetData("SELECT * FROM State WHERE country_id=" + dsEvent.Tables[0].Rows[0]["CatCountry"].ToString());

            isFeatured.Text = dsEvent.Tables[0].Rows[0]["Featured"].ToString();

            if (DateTime.Parse(dsCalendar.Tables[0].Rows[0]["DateTimeStart"].ToString()) < StartDateTimePicker.MinDate)
                StartDateTimePicker.DbSelectedDate = StartDateTimePicker.MinDate;
            else
                StartDateTimePicker.DbSelectedDate = DateTime.Parse(dsCalendar.Tables[0].Rows[0]["DateTimeStart"].ToString());

            TimeSpan abc = DateTime.Parse(dsCalendar.Tables[0].Rows[0]["DateTimeEnd"].ToString()).Subtract(DateTime.Parse(dsCalendar.Tables[0].Rows[0]["DateTimeStart"].ToString()));

            DaysDropDown.SelectedValue = abc.Days.ToString();

            CountryDropDown.SelectedValue = dsEvent.Tables[0].Rows[0]["CatCountry"].ToString();

            bool isTextBox = false;

            if (dsEvent.Tables[0].Rows[0]["CatState"] != null)
            {

                DataSet dsState = dat.GetData("SELECT * FROM State WHERE country_id=" + dsEvent.Tables[0].Rows[0]["CatCountry"].ToString());

                if (dsState.Tables.Count > 0)
                    if (dsState.Tables[0].Rows.Count > 0)
                    {
                        StateDropDownPanel.Visible = true;
                        StateTextBoxPanel.Visible = false;
                        StateDropDown.DataSource = dsState;
                        StateDropDown.DataTextField = "state_2_code";
                        StateDropDown.DataValueField = "state_id";
                        StateDropDown.DataBind();

                        StateDropDown.Items.FindByText(dsEvent.Tables[0].Rows[0]["CatState"].ToString()).Selected = true;
                    }
                    else
                        isTextBox = true;
                else
                    isTextBox = true;

                if (isTextBox)
                {
                    StateTextBoxPanel.Visible = true;
                    StateDropDownPanel.Visible = false;
                    StateTextBox.THE_TEXT = dsEvent.Tables[0].Rows[0]["CatState"].ToString();

                }
            }

            if (dsEvent.Tables[0].Rows[0]["CatCity"] != null)
            {
                CityTextBox.Text = dsEvent.Tables[0].Rows[0]["CatCity"].ToString();
            }

            if (dsEvent.Tables[0].Rows[0]["CatZip"] != null)
            {
                if (dsEvent.Tables[0].Rows[0]["CatZip"].ToString().Trim() != "")
                {
                    char[] delim2 = { ';' };
                    string[] tokens2 = dsEvent.Tables[0].Rows[0]["CatZip"].ToString().Split(delim2);
                    ZipTextBox.Text = tokens2[1];
                }
            }

            if (dsEvent.Tables[0].Rows[0]["Radius"] != null)
            {
                RadiusDropDown.SelectedValue = dsEvent.Tables[0].Rows[0]["Radius"].ToString();
            }

            DescriptionTextBox.Content = dsEvent.Tables[0].Rows[0]["Description"].ToString();

            if (bool.Parse(dsEvent.Tables[0].Rows[0]["DisplayToAll"].ToString()))
                DisplayCheckList.SelectedValue = "1";
            else
                DisplayCheckList.SelectedValue = "2";

            if (bool.Parse(dsEvent.Tables[0].Rows[0]["Featured"].ToString()))
            {

                if(!iscopy)
                    DateCannotEditLabel.Text = "You cannot edit the date for a featured ad.<br/>";

                if(isedit && !iscopy)
                    StartDateTimePicker.Enabled = false;
                SummaryTextBox.InnerHtml = dsEvent.Tables[0].Rows[0]["FeaturedSummary"].ToString();

                SelectFeatured();

                AdMediaPanel.Enabled = true;
                AdMediaPanel.Visible = true;
                AdPictureCheckList.Items.Clear();
                if (dsEvent.Tables[0].Rows[0]["FeaturedPicture"] != null)
                {
                    if (dsEvent.Tables[0].Rows[0]["FeaturedPicture"].ToString().Trim() != "")
                    {
                        ListItem newItem = new ListItem(dsEvent.Tables[0].Rows[0]["FeaturedPictureName"].ToString(),
                            dsEvent.Tables[0].Rows[0]["FeaturedPicture"].ToString());
                        AdPictureCheckList.Items.Add(newItem);

                        AdNixItButton.Visible = true;

                        BannerAdCheckBox.Checked = true;
                    }
                    else
                    {
                        AdPictureCheckList.Items.Clear();

                        AdNixItButton.Visible = false;
                        BannerAdCheckBox.Checked = false;
                    }
                }
                else
                {
                    AdPictureCheckList.Items.Clear();

                    AdNixItButton.Visible = false;
                    BannerAdCheckBox.Checked = false;
                }
            }
            else
            {
                SelectFree();
            }

            //InfoPanelFeaturedLabel.Visible = false;
            //InfoPanelFreeLabel.Visible = false;

            PictureCheckList.Items.Clear();
            string mediaCategory = dsEvent.Tables[0].Rows[0]["mediaCategory"].ToString();
            string youtube = dsEvent.Tables[0].Rows[0]["YouTubeVideo"].ToString();
            switch (mediaCategory)
            {
                case "1":
                    MainAttractionCheck.Checked = true;
                    char[] delim4 = { ';' };
                    char[] delim = { '\\' };
                    string[] youtokens = youtube.Split(delim4);
                    if (youtokens.Length > 0)
                    {
                        for (int i = 0; i < youtokens.Length; i++)
                        {
                            if (youtokens[i].Trim() != "")
                            {
                                ListItem newListItem = new ListItem("You Tube ID: " + youtokens[i],
                                    youtokens[i]);

                                PictureCheckList.Items.Add(newListItem);
                            }
                        }
                    }
                    string[] fileArray = System.IO.Directory.GetFiles(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString()
                        + "\\AdSlider\\" + ID);
                    DataView dvA = dat.GetDataDV("SELECT * FROM Ad_Slider_Mapping WHERE AdID=" + ID);
                    for (int i = 0; i < dvA.Count; i++)
                    {
                        string[] fileTokens = fileArray[i].Split(delim);
                        string nameFile = dvA[i]["PictureName"].ToString();

                        ListItem newListItem = new ListItem(dvA[i]["RealPictureName"].ToString(),
                                nameFile);

                            PictureCheckList.Items.Add(newListItem);

                    }
                    YouTubePanel.Enabled = true;
                    PicturePanel.Enabled = true;
                    PictureCheckList.Enabled = true;
                    PictureNixItButton.Visible = true;
                    break;
                default: break;
            }

            DataSet dsMusic = dat.GetData("SELECT * FROM Ad_Song_Mapping WHERE AdID=" + dsEvent.Tables[0].Rows[0]["Ad_ID"].ToString());
            SongCheckList.Items.Clear();
            if (dsMusic.Tables.Count > 0)
                if (dsMusic.Tables[0].Rows.Count > 0)
                {
                    MusicPanel.Enabled = true;
                    for (int i = 0; i < dsMusic.Tables[0].Rows.Count; i++)
                    {
                        SongCheckList.Enabled = true;
                        DeleteSongButton.Visible = true;
                        MusicCheckBox.Checked = true;
                        ListItem newItem = new ListItem(dsMusic.Tables[0].Rows[i]["SongTitle"].ToString(),
                            dsMusic.Tables[0].Rows[i]["SongName"].ToString());

                        SongCheckList.Items.Add(newItem);
                    }
                }

            DataSet dsCategories = dat.GetData("SELECT * FROM Ad_Category_Mapping WHERE AdID=" + ID);

            if (dsCategories.Tables.Count > 0)
                if (dsCategories.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < dsCategories.Tables[0].Rows.Count; i++)
                    {
                        Telerik.Web.UI.RadTreeNode node =
                            (Telerik.Web.UI.RadTreeNode)CategoryTree.Nodes.FindNodeByValue(dsCategories.Tables[0].Rows[i]["CategoryID"].ToString());
                        if (node != null)
                        {
                            node.Checked = true;
                        }
                        else
                        {

                            node = (Telerik.Web.UI.RadTreeNode)RadTreeView1.Nodes.FindNodeByValue(dsCategories.Tables[0].Rows[i]["CategoryID"].ToString());
                            if (node != null)
                            {
                                node.Checked = true;
                            }
                            else
                            {

                                node = (Telerik.Web.UI.RadTreeNode)RadTreeView2.Nodes.FindNodeByValue(dsCategories.Tables[0].Rows[i]["CategoryID"].ToString());
                                if (node != null)
                                {
                                    node.Checked = true;
                                }
                                else
                                {
                                    node = (Telerik.Web.UI.RadTreeNode)RadTreeView3.Nodes.FindNodeByValue(dsCategories.Tables[0].Rows[i]["CategoryID"].ToString());
                                    if (node != null)
                                    {
                                        node.Checked = true;
                                    }

                                }

                            }
                        }
                        //CategoriesCheckBoxes.Items.FindByValue(dsCategories.Tables[0].Rows[i]["CategoryID"].ToString()).Selected = true;
                        //CategoriesCheckBoxes.Items.FindByValue(dsCategories.Tables[0].Rows[i]["CategoryID"].ToString()).Enabled = false;
                    }
                }

            if (!iscopy)
            {
                PaidForPanel.Visible = true;
                AdPlacementList.Enabled = false;
                NotEditLabel.Text = "You are not allowed to edit this part.";
                NumberOfPaidUsers.Text = dsEvent.Tables[0].Rows[0]["NumViews"].ToString() + "<br/>";
            }
            DataView dvAdControl = dat.GetDataDV("SELECT * FROM AdControl");

            if (bool.Parse(dsEvent.Tables[0].Rows[0]["BigAd"].ToString()))
            {
                AdPlacementList.SelectedValue = "0.04";

                RadToolTip2.Text = "<label>Your price will be calulated based on the number of " +
                "users you want your ad to be displayed to. Your ad will stop running " +
                "when that particular number of users have seen your ad. The price for " +
                "each user is $0.04, since you have chosen the 'Big Ad Space'. " +
                "For example, if you choose 1000 users, your cost will be $40.</label>";
                if (bool.Parse(dvAdControl[0]["areAdsFree"].ToString()))
                {
                    FreeLabel.Text = "Choose how many users you want to see your ad. " +
                        " <span style='color: #ff770d;'>[As the ads are now free, your limit on the "+
                        "number of users you can choose is " +
                        dvAdControl[0]["bigUserLimit"].ToString() + ".]</span>Your price will be calulated based on the number of " +
                "users you want your ad to be displayed to. Your ad will stop running " +
                "when that particular number of users have seen your ad. The price for " +
                "each user is $0.04, since you have chosen the 'Big Ad Space'. " +
                "For example, if you choose 1000 users, your cost will be $40.";
                    FreeValidator.MaximumValue = dvAdControl[0]["bigUserLimit"].ToString();
                    FreeValidator.ErrorMessage = "User count can only be between 0 and " +
                        dvAdControl[0]["bigUserLimit"].ToString() + ".";
                }
                else
                {
                    CalcPrice();
                    //GetAvailableUsers((DateTime)Session["SelectedStartDate"], true);
                }

            }
            else
            {
                AdPlacementList.SelectedValue = "0.01";
                RadToolTip2.Text = "<label>Your price will be calulated based on the number of " +
                    "users you want your ad to be displayed to. Your ad will stop running " +
                    "when that particular number of users have seen your ad. The price for " +
                    "each user is $0.01, since you have chosen a 'Normal Ad Space'. " +
                    "For example, if you choose 1000 users, your cost will be $10.</label>";

                if (bool.Parse(dvAdControl[0]["areAdsFree"].ToString()))
                {
                    FreeLabel.Text = "Choose how many users you want to see your ad. " +
                        " <span style='color: #ff770d;'>[As the ads are now free, your limit on the number of users you can choose is " +
                        dvAdControl[0]["userLimit"].ToString() + ".]</span> <br/>Your price will be calulated based on the number of " +
                    "users you want your ad to be displayed to. Your ad will stop running " +
                    "when that particular number of users have seen your ad. The price for " +
                    "each user is $0.01, since you have chosen a 'Normal Ad Space'. " +
                    "For example, if you choose 1000 users, your cost will be $10.";
                    Image6.Visible = true;
                    FreeValidator.MaximumValue = dvAdControl[0]["userLimit"].ToString();
                    FreeValidator.ErrorMessage = "User count can only be between 0 and " +
                        dvAdControl[0]["userLimit"].ToString() + ".";
                }
                else
                {
                    Image6.Visible = false;
                    CalcPrice();
                    //GetAvailableUsers((DateTime)Session["SelectedStartDate"], false);

                }
            }

            if (bool.Parse(dvAdControl[0]["areAdsFree"].ToString()))
            {
                if (!iscopy)
                {
                    UserNumberPanel.Enabled = false;
                    UserNumberLabel.Text = "<label>Since featured ads are now free. Allowed user count is restricted.</label>";
                }
                FreeValidator.MaximumValue = dvAdControl[0]["userLimit"].ToString();
                FreeValidator.ErrorMessage = "User count can only be between 0 and " +
                    dvAdControl[0]["userLimit"].ToString() + ".";
            }
            else
            {
                UserNumberPanel.Enabled = true;
                UserNumberLabel.Text = "";
            }
        }
        catch (Exception ex)
        {
            YourMessagesLabel.Text = ex.ToString();
            MessagePanel.Visible = true;
        }
    }