protected void Page_Load(object sender, EventArgs e) {
            var wt = new WebTools();
            codeEntryField.CssClass = wt.CssRemoveClass(codeEntryField.CssClass, "code-glow");

            if (!IsPostBack) {
                if(Session["Patron"] == null) {
                    Response.Redirect("~");
                }
                var patron = (Patron)Session[SessionKey.Patron];
                var program = Programs.FetchObject(patron.ProgID);

                if(program == null || !program.IsOpen) {
                    codeControlPanel.Visible = false;
                    return;
                }
                ViewState["PatronId"] = patron.PID.ToString();

                var storedCode = Session[SessionKey.SecretCode];
                if(storedCode != null && !string.IsNullOrWhiteSpace(storedCode.ToString()))
                {
                    codeEntryField.Text = storedCode.ToString();
                    codeEntryField.CssClass = wt.CssEnsureClass(codeEntryField.CssClass, "code-glow");
                
                    Session.Remove(SessionKey.SecretCode);
                    new SessionTools(Session).AlertPatron(
                        StringResources.getString("secret-code-link"),
                        PatronMessageLevels.Info,
                        "barcode");
                }
            }
        }
 protected void btnClear_Click(object sender, EventArgs e)
 {
     CategoryId.ClearSelection();
     AgeGroupId.ClearSelection();
     BranchId.ClearSelection();
     LocationID.ClearSelection();
     odsBadges.DataBind();
     rptr.DataBind();
     var wt = new WebTools();
     CategoryId.CssClass = wt.CssRemoveClass(CategoryId.CssClass, "gra-search-active");
     AgeGroupId.CssClass = wt.CssRemoveClass(AgeGroupId.CssClass, "gra-search-active");
     BranchId.CssClass = wt.CssRemoveClass(BranchId.CssClass, "gra-search-active");
     LocationID.CssClass = wt.CssRemoveClass(LocationID.CssClass, "gra-search-active");
 }
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            odsBadges.DataBind();
            rptr.DataBind();
            var wt = new WebTools();
            if (CategoryId.SelectedIndex > 0
                || AgeGroupId.SelectedIndex > 0
                || BranchId.SelectedIndex > 0
                || LocationID.SelectedIndex > 0)
            {
                CategoryId.CssClass = wt.CssEnsureClass(CategoryId.CssClass, "gra-search-active");
                AgeGroupId.CssClass = wt.CssEnsureClass(AgeGroupId.CssClass, "gra-search-active");
                BranchId.CssClass = wt.CssEnsureClass(BranchId.CssClass, "gra-search-active");
                LocationID.CssClass = wt.CssEnsureClass(LocationID.CssClass, "gra-search-active");
            }
            else
            {
                CategoryId.CssClass = wt.CssRemoveClass(CategoryId.CssClass, "gra-search-active");
                AgeGroupId.CssClass = wt.CssRemoveClass(AgeGroupId.CssClass, "gra-search-active");
                BranchId.CssClass = wt.CssRemoveClass(BranchId.CssClass, "gra-search-active");
                LocationID.CssClass = wt.CssRemoveClass(LocationID.CssClass, "gra-search-active");

            }
        }
        protected void ClearSearch(object sender, EventArgs e)
        {
            SearchText.Text = string.Empty;
            BranchId.SelectedIndex = 0;
            var wt = new WebTools();

            BranchId.CssClass = wt.CssRemoveClass(BranchId.CssClass, "gra-search-active");
            SearchText.CssClass = wt.CssRemoveClass(SearchText.CssClass, "gra-search-active");
            LoadData();
        }
        protected void Search(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(SearchText.Text))
            {
                SearchText.Text = string.Empty;
            }

            var wt = new WebTools();
            if (!string.IsNullOrEmpty(SearchText.Text) || BranchId.SelectedIndex > 0)
            {
                BranchId.CssClass = wt.CssEnsureClass(BranchId.CssClass, "gra-search-active");
                SearchText.CssClass = wt.CssEnsureClass(SearchText.CssClass, "gra-search-active");
            }
            else
            {
                BranchId.CssClass = wt.CssRemoveClass(BranchId.CssClass, "gra-search-active");
                SearchText.CssClass = wt.CssRemoveClass(SearchText.CssClass, "gra-search-active");
            }
            LoadData();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Request["PID"]))
            {
                Session["ProgramID"] = Request["PID"].ToString();
            }
            if (!IsPostBack)
            {
                if (Session["ProgramID"] == null)
                {
                    try
                    {
                        int PID = Programs.GetDefaultProgramID();
                        Session["ProgramID"] = PID.ToString();
                    }
                    catch
                    {
                        Response.Redirect("~/Default.aspx");
                    }
                }
            }

            TranslateStrings(this);

            eventBackLink.NavigateUrl = "~/Events/";

            DAL.Event evnt = null;
            int eventId = 0;
            string displayEvent = Request.QueryString["EventId"];
            if (!string.IsNullOrEmpty(displayEvent)
               && int.TryParse(displayEvent.ToString(), out eventId))
            {
                evnt = DAL.Event.GetEvent(eventId);
                if (evnt != null && evnt.HiddenFromPublic)
                {
                    evnt = null;
                }
                if (evnt != null)
                {
                    SchemaOrgLibrary mdLib = new SchemaOrgLibrary();
                    SchemaOrgEvent mvEvt = new SchemaOrgEvent
                    {
                        Name = evnt.EventTitle,
                        StartDate = evnt.EventDate
                    };

                    eventTitle.Text = evnt.EventTitle;
                    this.Title = string.Format("Event Details: {0}", eventTitle.Text);

                    eventWhen.Text = DAL.Event.DisplayEventDateTime(evnt);

                    eventWhere.Visible = false;
                    eventWhereLink.Visible = false;
                    atLabel.Visible = false;

                    if (evnt.BranchID > 0)
                    {
                        var codeObject = DAL.Codes.FetchObject(evnt.BranchID);
                        if (codeObject != null)
                        {
                            eventWhere.Text
                                = mdLib.Name
                                = codeObject.Description;
                            eventWhereLink.Text = string.Format("{0} <span class=\"glyphicon glyphicon-new-window hidden-print\"></span>",
                                codeObject.Description);

                            eventWhere.Visible = true;
                            atLabel.Visible = true;
                            eventWhereLink.Visible = false;
                        }
                        var crosswalk = DAL.LibraryCrosswalk.FetchObjectByLibraryID(evnt.BranchID);
                        if (crosswalk != null)
                        {
                            if (!string.IsNullOrEmpty(eventWhere.Text)
                                && !string.IsNullOrEmpty(crosswalk.BranchAddress))
                            {
                                eventWhereMapLink.Visible = true;
                                eventWhereMapLink.NavigateUrl = string.Format(WebTools.BranchMapLinkStub,
                                    crosswalk.BranchAddress);
                            }

                            if (!string.IsNullOrEmpty(eventWhere.Text)
                               && !string.IsNullOrEmpty(crosswalk.BranchLink))
                            {
                                eventWhereLink.NavigateUrl = crosswalk.BranchLink;
                                eventWhere.Visible = false;
                                eventWhereLink.Visible = true;
                                atLabel.Visible = true;
                            }

                            mdLib.Address = crosswalk.BranchAddress;
                            mdLib.Telephone = crosswalk.BranchTelephone;
                            mdLib.Url = crosswalk.BranchLink;
                        }
                    }

                    if (string.IsNullOrEmpty(mdLib.Name))
                    {
                        this.MetaDescription = string.Format("Details about the event: {0} - {1}",
                            mdLib.Name,
                            GetResourceString("system-name"));
                    }
                    else
                    {
                        this.MetaDescription = string.Format("Details about the event: {0} at {1} - {2}",
                            eventTitle.Text,
                            eventWhere.Text,
                            GetResourceString("system-name"));
                    }

                    if (!string.IsNullOrWhiteSpace(evnt.ExternalLinkToEvent))
                    {
                        eventLinkPanel.Visible = true;
                        ExternalLink.NavigateUrl = evnt.ExternalLinkToEvent;
                        ExternalLink.Text = string.Format(eventTitle.Text);
                    }
                    else
                    {
                        eventLinkPanel.Visible = false;
                    }
                    eventDescription.Text = Server.HtmlDecode(evnt.HTML);
                    var cf = DAL.CustomEventFields.FetchObject();
                    if (!string.IsNullOrWhiteSpace(evnt.Custom1)
                       && !string.IsNullOrWhiteSpace(cf.Label1))
                    {
                        eventCustom1Panel.Visible = true;
                        eventCustomLabel1.Text = cf.Label1;
                        eventCustomValue1.Text = evnt.Custom1;
                    }
                    else
                    {
                        eventCustom1Panel.Visible = false;
                    }
                    if (!string.IsNullOrWhiteSpace(evnt.Custom2)
                       && !string.IsNullOrWhiteSpace(cf.Label2))
                    {
                        eventCustom2Panel.Visible = true;
                        eventCustomLabel2.Text = cf.Label2;
                        eventCustomValue2.Text = evnt.Custom2;
                    }
                    else
                    {
                        eventCustom2Panel.Visible = false;
                    }
                    if (!string.IsNullOrWhiteSpace(evnt.Custom3)
                       && !string.IsNullOrWhiteSpace(cf.Label3))
                    {
                        eventCustom3Panel.Visible = true;
                        eventCustomLabel3.Text = cf.Label3;
                        eventCustomValue3.Text = evnt.Custom3;
                    }
                    else
                    {
                        eventCustom3Panel.Visible = false;
                    }
                    eventDetails.Visible = true;

                    mvEvt.Location = mdLib;
                    try
                    {
                        Microdata.Text = new WebTools().BuildEventJsonld(mvEvt);
                    }
                    catch (Exception ex)
                    {
                        this.Log().Error("Problem creating microdata in event detail for {0}: {1} - {2}",
                            evnt.EID,
                            ex.Message,
                            ex.StackTrace);
                    }

                    // begin social
                    var wt = new WebTools();

                    var systemName = StringResources.getStringOrNull("system-name");
                    var fbDescription = StringResources.getStringOrNull("facebook-description");
                    var hashtags = StringResources.getStringOrNull("socialmedia-hashtags");

                    var title = string.Format("{0} event: {1}",
                        systemName,
                        evnt.EventTitle);
                    string description = string.Format("I'm thinking about attending this {0} event: {1}!",
                        systemName,
                        evnt.EventTitle);
                    string twitDescrip = string.Format("Check out this {0} event: {1}!",
                        systemName,
                        evnt.EventTitle);
                    if (twitDescrip.Length > 118)
                    {
                        // if it's longer than this it won't fit with the url, shorten it
                        twitDescrip = string.Format("Check this out: {0}!",
                            evnt.EventTitle);
                    }

                    var baseUrl = WebTools.GetBaseUrl(Request);
                    var eventDetailsUrl = string.Format("{0}/Events/Details.aspx?EventId={1}",
                        baseUrl,
                        evnt.EID);
                    string bannerPath = new GRA.Logic.Banner().FullMetadataBannerPath(baseUrl,
                        Session,
                        Server);

                    wt.AddOgMetadata(Metadata,
                        title,
                        wt.BuildFacebookDescription(description, hashtags, fbDescription),
                        bannerPath,
                        eventDetailsUrl,
                        facebookApp: GetResourceString("facebook-appid"));

                    wt.AddTwitterMetadata(Metadata,
                        title,
                        description,
                        bannerPath,
                        twitterUsername: GetResourceString("twitter-username"));

                    TwitterShare.NavigateUrl = wt.GetTwitterLink(twitDescrip,
                        Server.UrlEncode(eventDetailsUrl),
                        hashtags);
                    TwitterShare.Visible = true;
                    FacebookShare.NavigateUrl
                        = wt.GetFacebookLink(Server.UrlEncode(eventDetailsUrl));
                    FacebookShare.Visible = true;
                    //end social
                }
            }

            if (evnt == null)
            {
                eventDetails.Visible = false;
                var cph = Page.Master.FindControl("HeaderContent") as ContentPlaceHolder;
                if (cph != null)
                {
                    cph.Controls.Add(new HtmlMeta
                    {
                        Name = "robots",
                        Content = "noindex"
                    });
                }
                Session[SessionKey.PatronMessage] = "Could not find details on that event.";
                Session[SessionKey.PatronMessageLevel] = PatronMessageLevels.Warning;
                Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign";

            }
        }
        protected void btnEmail_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(PUsername.Text.Trim()))
            {
                var patron = Patron.GetObjectByUsername(PUsername.Text.Trim());

                if (patron == null || string.IsNullOrEmpty(patron.EmailAddress))
                {
                    new SessionTools(Session).AlertPatron("Your account could not be located or is not associated with an email address. Please visit your local library branch to reset your password.", PatronMessageLevels.Warning, "exclamation-sign");
                    if (patron != null)
                    {
                        this.Log().Info("Unable to send password recovery email for patron id {0} becuase they don't have an email address configured", patron.PID);
                    }
                    return;
                }
                else {
                    try
                    {
                        string remoteAddress = new WebTools().RemoteUserAddress(Request);

                        string passwordResetToken = patron.GeneratePasswordResetToken();
                        if (string.IsNullOrEmpty(passwordResetToken))
                        {
                            new SessionTools(Session).AlertPatron("Unable to reset your password. Please visit your local library branch.", PatronMessageLevels.Warning, "exclamation-sign");
                            this.Log().Fatal("Unable to generate password reset token - critical error in password recovery");
                            return;
                        }

                        string systemName = SRPSettings.GetSettingValue("SysName");

                        var values = new
                        {
                            SystemName = systemName,
                            PasswordResetLink = string.Format("{0}{1}?token={2}",
                                                              WebTools.GetBaseUrl(Request),
                                                              "/PasswordRecovery.aspx",
                                                              passwordResetToken),
                            ContactName = SRPSettings.GetSettingValue("ContactName"),
                            ContactEmail = SRPSettings.GetSettingValue("ContactEmail"),
                            RemoteAddress = remoteAddress,
                            UserEmail = patron.EmailAddress,
                            Username = patron.Username,
                            PasswordResetSubject = string.Format("{0} password reset request", systemName)
                        };

                        StringBuilder body = new StringBuilder();
                        body.Append("<p>A password reset request was received by {SystemName} for ");
                        body.Append("your account: {Username}.</p><p>Please ");
                        body.Append("<a href=\"{PasswordResetLink}\">click here</a> ");
                        body.Append("to create a new password for your account.</p>");
                        body.Append("<p>If you did not initiate this request, take no action and your ");
                        body.Append("password will not be changed.</p>");
                        body.Append("<p>If you have any comments or questions, please contact ");
                        body.Append("{ContactName} at ");
                        body.Append("<a href=\"mailto:{ContactEmail}\">{ContactEmail}</a>.</p>");
                        body.Append("<p style=\"font-size: smaller;\"><em>This password request was ");
                        body.Append("submitted from: {RemoteAddress}.</em></p>");

                        new EmailService().SendEmail(patron.EmailAddress,
                                                     "{SystemName} - {PasswordResetSubject}".FormatWith(values),
                                                     body.ToString().FormatWith(values));
                        this.Log().Info("Sent password request email for patron id {0} to {1}",
                            patron.PID, patron.EmailAddress);

                        new SessionTools(Session).AlertPatron("Processing your password reset request, you should receive an email soon.",
                            glyphicon: "ok");
                    }
                    catch (Exception ex)
                    {
                        this.Log().Fatal("Unable to send password recovery email for patron id {0} to {1}: {2} - {3}",
                            patron.PID,
                            patron.EmailAddress,
                            ex.Message,
                            ex.StackTrace);
                        new SessionTools(Session).AlertPatron("A problem occurred resetting your password. Please visit your local library branch to reset your password.",
                            PatronMessageLevels.Warning,
                            "exclamation-sign");
                    }
                }

                new SessionTools(Session).ClearPatron();
                Response.Redirect("~");
            }
        }
 protected void PopulateChallengeList()
 {
     int patronId = -1;
     if (this.CurrentPatron != null)
     {
         patronId = this.CurrentPatron.PID;
     }
     Filtered = !string.IsNullOrWhiteSpace(SearchText.Text);
     var ds = DAL.BookList.GetForDisplay(patronId, SearchText.Text);
     rptr.DataSource = ds;
     rptr.DataBind();
     var wt = new WebTools();
     if (ds.Tables[0].Rows.Count == 0)
     {
         ChallengesContainer.Visible = false;
         if (Filtered)
         {
             WhatsShowing.Text
                 = WhatsShowingPrint.Text
                 = StringResources.getString("challenges-no-match");
             WhatsShowingPanel.Visible = true;
             WhatsShowingPanel.CssClass = wt.CssRemoveClass(WhatsShowingPanel.CssClass,
                 "alert-success");
             WhatsShowingPanel.CssClass = wt.CssEnsureClass(WhatsShowingPanel.CssClass,
                 "alert-warning");
         }
         else
         {
             WhatsShowing.Text
                 = WhatsShowingPrint.Text
                 = StringResources.getString("challenges-no-challenges");
             WhatsShowingPanel.Visible = true;
             WhatsShowingPanel.CssClass = wt.CssRemoveClass(WhatsShowingPanel.CssClass,
                 "alert-success");
             WhatsShowingPanel.CssClass = wt.CssEnsureClass(WhatsShowingPanel.CssClass,
                 "alert-warning");
         }
     }
     else
     {
         ChallengesContainer.Visible = true;
         if (Filtered)
         {
             WhatsShowing.Text
                 = WhatsShowingPrint.Text
                 = string.Format("You searched for: <strong>{0}</strong>", SearchText.Text);
             WhatsShowingPanel.Visible = true;
             WhatsShowingPanel.CssClass
                 = wt.CssRemoveClass(WhatsShowingPanel.CssClass, "alert-warning");
             WhatsShowingPanel.CssClass
                 = wt.CssEnsureClass(WhatsShowingPanel.CssClass, "alert-success");
         }
         else
         {
             WhatsShowing.Text
                 = WhatsShowingPrint.Text
                 = string.Empty;
             WhatsShowingPanel.Visible = false;
         }
     }
     if (Filtered)
     {
         SearchText.CssClass
             = wt.CssEnsureClass(SearchText.CssClass, "gra-search-active");
     }
     else
     {
         SearchText.CssClass
             = wt.CssRemoveClass(SearchText.CssClass, "gra-search-active");
     }
 }
        protected void DoFilter(EventSearchCriteria criteria)
        {
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(criteria.StartDate))
            {
                sb.Append("Start Date: ");
                sb.Append("<strong>");
                sb.Append(criteria.StartDate);
                sb.Append("</strong>");
            }
            if (!string.IsNullOrEmpty(criteria.EndDate))
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("End date: ");
                sb.Append("<strong>");
                sb.Append(criteria.EndDate);
                sb.Append("</strong>");
            }
            if (criteria.SystemId > 0)
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("System: ");
                sb.Append("<strong>");
                sb.Append(SystemId.Items.FindByValue(criteria.SystemId.ToString()).Text);
                sb.Append("</strong>");
            }
            if (criteria.BranchId > 0)
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("Branch/library: ");
                sb.Append("<strong>");
                sb.Append(criteria.BranchName);
                sb.Append("</strong>");
            }
            if (!string.IsNullOrWhiteSpace(criteria.SearchText))
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("Search text: ");
                sb.Append("<strong>");
                sb.Append(criteria.SearchText);
                sb.Append("</strong>");
            }

            WhatsShowing.Text = WhatsShowingPrint.Text = sb.ToString();
            WhatsShowingPanel.Visible = Filtered = !string.IsNullOrEmpty(WhatsShowing.Text);

            if (string.IsNullOrEmpty(WhatsShowing.Text))
            {
                // no filter criteria, use cache if possible
                var st = new SessionTools(Session);
                var cachedEvents = st.GetCache(Cache, CacheKey.AllEvents) as System.Data.DataSet;
                if (cachedEvents != null)
                {
                    rptr.DataSource = cachedEvents;
                }
                else
                {
                    var allEvents = Event.GetUpcomingDisplay(
                        criteria.StartDate,
                        criteria.EndDate,
                        criteria.SystemId,
                        criteria.BranchId,
                        criteria.SearchText);
                    rptr.DataSource = allEvents;

                    string tenantCacheKey = st.GetTenantCacheKey(CacheKey.AllEvents);
                    Cache.Insert(tenantCacheKey,
                        allEvents,
                        null,
                        DateTime.UtcNow.AddHours(2),
                        System.Web.Caching.Cache.NoSlidingExpiration,
                        System.Web.Caching.CacheItemPriority.Default,
                        null);
                }
            }
            else
            {
                rptr.DataSource = Event.GetUpcomingDisplay(
                    criteria.StartDate,
                    criteria.EndDate,
                    criteria.SystemId,
                    criteria.BranchId,
                    criteria.SearchText);
            }
            rptr.DataBind();

            var wt = new WebTools();
            if (Filtered)
            {
                StartDate.CssClass = wt.CssEnsureClass(StartDate.CssClass, "gra-search-active");
                EndDate.CssClass = wt.CssEnsureClass(EndDate.CssClass, "gra-search-active");
                BranchId.CssClass = wt.CssEnsureClass(BranchId.CssClass, "gra-search-active");
                SystemId.CssClass = wt.CssEnsureClass(SystemId.CssClass, "gra-search-active");
                SearchText.CssClass = wt.CssEnsureClass(SearchText.CssClass, "gra-search-active");
            }
            else
            {
                StartDate.CssClass = wt.CssRemoveClass(StartDate.CssClass, "gra-search-active");
                EndDate.CssClass = wt.CssRemoveClass(EndDate.CssClass, "gra-search-active");
                BranchId.CssClass = wt.CssRemoveClass(BranchId.CssClass, "gra-search-active");
                SystemId.CssClass = wt.CssRemoveClass(SystemId.CssClass, "gra-search-active");
                SearchText.CssClass = wt.CssRemoveClass(SearchText.CssClass, "gra-search-active");
            }
        }
        protected void LookupChallenge(int blid)
        {
            var bl = BookList.FetchObject(blid);

            if (bl == null)
            {
                challengeDetails.Visible = false;
                new SessionTools(Session).AlertPatron("Could not find details on that Challenge.",
                    PatronMessageLevels.Warning,
                    "exclamation-sign");
            }
            else
            {
                int patronId = -1;
                var p = Session[SessionKey.Patron] as Patron;
                if (p != null)
                {
                    patronId = p.PID;
                }

                // see if this is bound to a specific program
                if (bl.ProgID != 0)
                {
                    // no user is logged in, don't show it
                    if (p == null)
                    {
                        var prog = DAL.Programs.FetchObject(bl.ProgID);
                        challengeDetails.Visible = false;
                        new SessionTools(Session).AlertPatron(
                            string.Format("You must be registered in the <strong>{0}</strong> program to view this Challenge.",
                                prog.TabName),
                            PatronMessageLevels.Warning,
                            "exclamation-sign");
                    }

                    // user is registered under another program
                    if (p != null && bl.ProgID != p.ProgID)
                    {
                        var prog = DAL.Programs.FetchObject(bl.ProgID);
                        challengeDetails.Visible = false;
                        new SessionTools(Session).AlertPatron(
                            string.Format("That Challenge is only available to people in the <strong>{0}</strong> program.",
                                prog.TabName),
                            PatronMessageLevels.Warning,
                            "exclamation-sign");
                    }
                }

                if (challengeDetails.Visible)
                {
                    Badge badge = null;

                    challengeTitle.Text = bl.ListName;
                    this.Title = string.Format("Challenge: {0}", challengeTitle.Text);
                    lblDesc.Text = string.Format("<p>{0}</p>", Server.HtmlDecode(bl.Description));

                    string award = null;

                    if (bl.AwardPoints > 0)
                    {
                        award = string.Format("Completing <strong>{0} task{1}</strong> will earn: <strong>{2} point{3}</strong>",
                            bl.NumBooksToComplete,
                            bl.NumBooksToComplete > 1 ? "s" : string.Empty,
                            bl.AwardPoints,
                            bl.AwardPoints > 1 ? "s" : string.Empty);
                    }

                    if (bl.AwardBadgeID > 0)
                    {
                        badge = DAL.Badge.FetchObject(bl.AwardBadgeID);
                        if (badge != null)
                        {
                            if (badge.HiddenFromPublic != true)
                            {
                                if (string.IsNullOrWhiteSpace(award))
                                {
                                    award = string.Format("Completing {0} task{1} will earn: <strong>a badge</strong>.",
                                        bl.NumBooksToComplete,
                                        bl.NumBooksToComplete > 1 ? "s" : string.Empty);
                                }
                                else
                                {
                                    award += " and <strong>a badge</strong>.";
                                }

                                BadgeImage.Text = string.Format("<img class=\"thumbnail disabled\" src=\"/images/badges/sm_{0}.png\" />", bl.AwardBadgeID);
                            }
                            else
                            {
                                badge = null;
                                if (string.IsNullOrWhiteSpace(award))
                                {
                                    award = string.Format("Completing {0} task{1} will earn: <strong>a secret badge</strong>.",
                                        bl.NumBooksToComplete,
                                        bl.NumBooksToComplete > 1 ? "s" : string.Empty);
                                }
                                else
                                {
                                    award += " and <strong>a secret badge</strong>.";
                                }
                                BadgeImage.Text = string.Empty;
                            }
                        }
                    }
                    else
                    {
                        BadgeImage.Text = string.Empty;
                        award += ".";
                    }

                    BadgeImage.Visible = !string.IsNullOrEmpty(BadgeImage.Text);

                    if (!string.IsNullOrWhiteSpace(award))
                    {
                        lblPoints.Text = award;
                        lblPoints.Visible = true;
                    }

                    var ds = BookListBooks.GetForDisplay(bl.BLID, patronId);

                    //Eval("NumBooksCompleted"), Eval("NumBooksToComplete")
                    if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        int completed = 0;
                        foreach(DataRow row in ds.Tables[0].Rows) {
                            if ((bool?)row["HasRead"] == true)
                            {
                                completed++;
                                if(completed >= bl.NumBooksToComplete)
                                {
                                    ChallengeCompleted = true;
                                    break;
                                }
                            }
                        }
                    }

                    rptr.DataSource = ds;
                    rptr.DataBind();

                    // begin social
                    var wt = new WebTools();

                    string systemName = StringResources.getStringOrNull("system-name");
                    var fbDescription = StringResources.getStringOrNull("facebook-description");
                    var hashtags = StringResources.getStringOrNull("socialmedia-hashtags");

                    string title = string.Format("{0} challenge: {1}",
                        systemName,
                        bl.ListName);

                    string description = string.Format("Check out this {0} challenge: {1}!",
                        systemName,
                        bl.ListName);

                    string twitDescrip = description;
                    if (twitDescrip.Length > 118)
                    {
                        // if it's longer than this it won't fit with the url, shorten it
                        twitDescrip = string.Format("Check this out: {0}!",
                            bl.ListName);
                    }

                    var baseUrl = WebTools.GetBaseUrl(Request);
                    var challengeUrl = string.Format("{0}/Challenges/Details.aspx?ChallengeId={1}",
                        baseUrl,
                        bl.BLID);

                    string imagePath = null;
                    if (badge != null)
                    {
                        string potentialBadgePath = string.Format("~/Images/Badges/{0}.png",
                                          badge.BID);
                        if (System.IO.File.Exists(Server.MapPath(potentialBadgePath)))
                        {
                            imagePath = string.Format("{0}{1}",
                                baseUrl,
                                VirtualPathUtility.ToAbsolute(potentialBadgePath));
                        }
                    }

                    if (string.IsNullOrEmpty(imagePath))
                    {
                        imagePath = new GRA.Logic.Banner().FullMetadataBannerPath(baseUrl,
                            Session,
                            Server);
                    }

                    wt.AddOgMetadata(Metadata,
                        title,
                        wt.BuildFacebookDescription(description, hashtags, fbDescription),
                        imagePath,
                        challengeUrl,
                        facebookApp: GetResourceString("facebook-appid"));

                    wt.AddTwitterMetadata(Metadata,
                        title,
                        description,
                        imagePath,
                        twitterUsername: GetResourceString("twitter-username"));

                    TwitterShare.NavigateUrl = wt.GetTwitterLink(description,
                        Server.UrlEncode(challengeUrl),
                        hashtags);
                    TwitterShare.Visible = true;
                    FacebookShare.NavigateUrl = wt.GetFacebookLink(Server.UrlEncode(challengeUrl));
                    FacebookShare.Visible = true;
                    // end social

                    this.ShowModal = true;
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Request["PID"]))
            {
                Session["ProgramID"] = Request["PID"].ToString();
            }
            if (!IsPostBack)
            {
                if (Session["ProgramID"] == null)
                {
                    try
                    {
                        int PID = Programs.GetDefaultProgramID();
                        Session["ProgramID"] = PID.ToString();
                    }
                    catch
                    {
                        Response.Redirect("~/Badges/");
                    }
                }
            }
            TranslateStrings(this);

            badgeBackLink.NavigateUrl = "~/Badges/";

            TwitterShare.Visible = false;
            FacebookShare.Visible = false;

            try
            {
                int badgeId = 0;
                string displayBadge = Request.QueryString["BadgeId"];
                if (!int.TryParse(displayBadge, out badgeId))
                {
                    throw new Exception("Invalid badge id provided.");
                }

                int patronId = 0;
                var patron = Session[SessionKey.Patron] as DAL.Patron;
                if (patron != null)
                {
                    patronId = patron.PID;
                }

                var badgeDetailData = new Logic.Badge().GetForDisplay(Server, badgeId, patronId);


                if (badgeDetailData.Hidden == true && badgeDetailData.Earned == false)
                {
                    throw new Exception("Secret badge must be earned to be revealed.");
                }

                badgeTitle.Text = badgeDetailData.DisplayName;
                this.Title = string.Format("Badge: {0}", badgeTitle.Text);
                this.MetaDescription = string.Format("All about the {0} badge - {1}",
                                                     badgeTitle.Text,
                                                     GetResourceString("system-name"));
                badgeImage.ImageUrl = badgeDetailData.ImageUrl;
                badgeImage.AlternateText = badgeDetailData.AlternateText;

                if (!string.IsNullOrEmpty(badgeDetailData.DateEarned))
                {
                    badgeEarnWhen.Text = string.Format("<p><strong>You earned this badge on {0}!</strong></p>",
                        badgeDetailData.DateEarned);
                    badgeEarnWhen.Visible = true;
                }
                else
                {
                    badgeEarnWhen.Visible = false;
                }

                badgeDetails.Visible = true;


                if (badgeDetailData.HowToEarn.Length > 0)
                {
                    badgeDesriptionLabel.Visible = true;
                    badgeDesriptionLabel.Text = this.Server.HtmlDecode(badgeDetailData.Description);
                }
                else
                {
                    badgeDesriptionLabel.Visible = false;
                }

                if (!badgeDetailData.HideDefaultDescription)
                {
                    badgeEarnPanel.Visible = true;

                    StringBuilder sb = new StringBuilder();
                    foreach (var line in badgeDetailData.HowToEarn)
                    {
                        sb.AppendFormat("<li>{0}</li>", line);
                    }
                    badgeEarnLabel.Text = sb.ToString();
                }
                else
                {
                    badgeEarnPanel.Visible = false;
                }

                /* metadata */
                string systemName = GetResourceString("system-name");
                var fbDescription = StringResources.getStringOrNull("facebook-description");
                var hashtags = StringResources.getStringOrNull("socialmedia-hashtags");

                string title = string.Format("{0} badge: {1}",
                    systemName,
                    badgeDetailData.DisplayName);
                string description = null;
                string twitDescrip = null;

                if (badgeDetailData.Earned)
                {
                    description = string.Format("By participating in {0} I earned this badge: {1}!",
                        systemName,
                        badgeDetailData.DisplayName);
                    twitDescrip = string.Format("I earned this {0} badge: {1}!",
                        systemName,
                        badgeDetailData.DisplayName);
                    if (twitDescrip.Length > 118)
                    {
                        // if it's longer than this it won't fit with the url, shorten it
                        twitDescrip = string.Format("I earned this badge: {0}!",
                            badgeDetailData.DisplayName);
                    }
                }
                else
                {
                    description = string.Format("By participating in {0} you can earn this badge: {1}!",
                        systemName,
                        badgeDetailData.DisplayName);
                    twitDescrip = string.Format("Check out this {0} badge: {1}!",
                        systemName,
                        badgeDetailData.DisplayName);
                    if (twitDescrip.Length > 118)
                    {
                        // if it's longer than this it won't fit with the url, shorten it
                        twitDescrip = string.Format("Check out this badge: {0}!",
                            badgeDetailData.DisplayName);
                    }
                }

                var wt = new WebTools();
                var baseUrl = WebTools.GetBaseUrl(Request);
                var badgeDetailsUrl = string.Format("{0}/Badges/Details.aspx?BadgeId={1}",
                    baseUrl,
                    badgeDetailData.BadgeId);
                var badgeImagePath = string.Format("{0}{1}", baseUrl,
                    VirtualPathUtility.ToAbsolute(badgeDetailData.ImageUrl));

                wt.AddOgMetadata(Metadata,
                    title,
                    wt.BuildFacebookDescription(description, hashtags, fbDescription),
                    badgeImagePath,
                    badgeDetailsUrl,
                    GetResourceString("facebook-appid"));

                wt.AddTwitterMetadata(Metadata,
                    title,
                    twitDescrip,
                    badgeImagePath,
                    twitterUsername: GetResourceString("twitter-username"));

                TwitterShare.NavigateUrl = wt.GetTwitterLink(twitDescrip,
                    Server.UrlEncode(badgeDetailsUrl),
                    hashtags);

                FacebookShare.NavigateUrl = wt.GetFacebookLink(Server.UrlEncode(badgeDetailsUrl));

                if (!badgeDetailData.Hidden)
                {
                    TwitterShare.Visible = true;
                    FacebookShare.Visible = true;
                }
                // end social
                badgeDetails.Visible = true;
            }
            catch (Exception)
            {
                badgeDetails.Visible = false;
                var cph = Page.Master.FindControl("HeaderContent") as ContentPlaceHolder;
                if (cph != null)
                {
                    cph.Controls.Add(new HtmlMeta
                    {
                        Name = "robots",
                        Content = "noindex"
                    });
                }
                new SessionTools(Session).AlertPatron("Could not find details on that badge.",
                    PatronMessageLevels.Warning,
                                                    "exclamation-sign");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (((BaseSRPPage)Page).IsLoggedIn)
            {
                Server.Transfer("~/Dashboard.aspx");
            }
            if (!String.IsNullOrEmpty(Request["PID"]))
            {
                Session["ProgramID"] = Request["PID"].ToString();
            }
            if (!IsPostBack)
            {
                if (Session["ProgramID"] == null)
                {
                    try
                    {
                        int PID = Programs.GetDefaultProgramID();
                        Session["ProgramID"] = PID.ToString();
                    }
                    catch
                    {
                        Response.Redirect("~/ControlRoom/Configure.aspx");
                    }
                    // pgmID.Text = Session["ProgramID"].ToString();
                }
                else
                {
                    //pgmID.Text = Session["ProgramID"].ToString();
                }

                var systemName = GetResourceString("system-name");
                var description = GetResourceString("frontpage-description");
                var wt = new WebTools();
                var baseUrl = WebTools.GetBaseUrl(Request);
                var bannerPath = new GRA.Logic.Banner().FullMetadataBannerPath(baseUrl,
                    Session,
                    Server);

                // open graph & facebook

                wt.AddOgMetadata(Metadata,
                    systemName,
                    description,
                    bannerPath,
                    baseUrl,
                    facebookApp: GetResourceString("facebook-appid"));

                // dublin core
                Metadata.Controls.Add(new HtmlMeta { Name = "DC.Title", Content = systemName });
                Metadata.Controls.Add(new HtmlMeta
                {
                    Name = "DC.Description",
                    Content = description
                });
                Metadata.Controls.Add(new HtmlMeta { Name = "DC.Source", Content = baseUrl });
                Metadata.Controls.Add(new HtmlMeta
                {
                    Name = "DC.Type",
                    Content = "InteractiveResource"
                });

                //twitter
                wt.AddTwitterMetadata(Metadata,
                    systemName,
                    GetResourceString("twitter-description"),
                    bannerPath,
                    "summary_large_image",
                    GetResourceString("twitter-username"));
            }
            TranslateStrings(this);
        }
        public void OnAuthenticate(object sender, AuthenticateEventArgs e)
        {
            if (Page.IsValid)
            {
                SRPUser user = new SRPUser();

                string remoteHost = new WebTools().RemoteUserAddress(Request);
                string remoteHostName = Request.UserHostName;
                if (Request.UserHostAddress == "127.0.0.1" || Request.UserHostAddress == "::1")
                {
                    remoteHostName = remoteHost;
                }

                bool auth = SRPUser.Login(uxLogin.UserName,
                                          uxLogin.Password, Session.SessionID,
                                          remoteHost,
                                          remoteHostName,
                                          string.Format("{0} - v{1}.{2}",
                                              Request.Browser.Browser,
                                              Request.Browser.MajorVersion,
                                              Request.Browser.MinorVersionString));
                if (!auth)
                {
                    uxMessageBox.Visible = true;
                    FailureText.Text = SRPResources.BadUserPass;
                    //Account Inactive
                    //
                    e.Authenticated = false;
                }
                else
                {
                    e.Authenticated = true;
                }


                if (e.Authenticated)
                {
                    // handle remember me
                    if (uxLogin.RememberMeSet == true)
                    {
                        var rememberMe = new HttpCookie("ControlRoomUsername", uxLogin.UserName);
                        rememberMe.Expires = DateTime.Now.AddDays(14);
                        Response.Cookies.Set(rememberMe);
                    }
                    else
                    {
                        var rememberMe = new HttpCookie("ControlRoomUsername", string.Empty);
                        rememberMe.Expires = DateTime.Now.AddDays(-1);
                        Response.Cookies.Set(rememberMe);
                    }

                    // Put User Profile into Session.
                    // Put Security roles into session
                    // = ConfigurationManager.AppSettings["ApplicationName"];
                    user = SRPUser.FetchByUsername(uxLogin.UserName);
                    Session[SessionData.IsLoggedIn.ToString()] = true;
                    Session[SessionData.UserProfile.ToString()] = user;

                    List<SRPPermission> perms = user.EffectiveUserPermissions();
                    //Session[SessionData.PermissionList.ToString()] = perms;
                    string permList = string.Empty;
                    foreach (SRPPermission perm in perms)
                        permList += String.Format("#{0}", perm.Permission);
                    Session[SessionData.StringPermissionList.ToString()] = permList;

                    Session["TenantID"] = user.TenID;
                    Session[CRSessionKey.TenantID] = user.TenID;
                    var tenant = Tenant.FetchObject(user.TenID);
                    Session[CRSessionKey.IsMaster] = tenant.isMasterFlag;


                    if (user.MustResetPassword)
                    {
                        this.Log().Info("Redirecting {0} to mandatory password reset.",
                                        user.Username);
                        Response.Redirect("~/ControlRoom/PasswordReset.aspx");
                    }
                    //List<CMSFolder> folders = user.EffectiveUserFolders();
                    //Session[SessionData.FoldersList.ToString()] = folders;
                    //string foldersList= string.Empty;
                    //foreach (CMSFolder folder in folders)
                    //    foldersList += string.Format("#{0}", folder.Folder);
                    //Session[SessionData.StringFoldersList.ToString()] = foldersList;


                    ////// to do - make sure these are in the settings module/ complete the settings module
                    ////string[] HideFolders =  new string[] { ".svn", "CVS", "app_data", "properties", "bin", "obj", "controls", "core", "controlroom", "app_themes" };
                    ////CMSSettings.SetSetting("HideFolders", HideFolders, ",");

                    ////string[]  HideFiles =   new string[] { ".*" };
                    ////CMSSettings.SetSetting("HideFiles", HideFiles, ",");

                    ////string[] AllowedExtensions = new string[] { };
                    ////CMSSettings.SetSetting("AllowedExtensions", AllowedExtensions, ",");

                    ////string[] DeniedExtensions = new string[] { };
                    ////CMSSettings.SetSetting("DeniedExtensions", DeniedExtensions, ",");
                    ////// end to do

                    FormsAuthentication.RedirectFromLoginPage(uxLogin.UserName, false);
                }
            }
            else
            {
                uxMessageBox.Visible = true;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            AvatarBackLink.NavigateUrl = "~/";

            SystemName.Text = SystemNamePrint.Text = StringResources.getString("system-name");
            SystemSlogan.Text = SystemSloganPrint.Text = StringResources.getString("slogan");
            SystemSlogan.Visible = SystemSloganPrint.Visible = SystemSlogan.Text != "slogan";
            string programId = null;

            AvatarBackLink.Text = StringResources.getString("avatar-return");
            if (AvatarBackLink.Text == "avatar-return")
            {
                AvatarBackLink.Text = "Back";
            }

            var patron = Session[SessionKey.Patron] as DAL.Patron;
            if (patron != null)
            {
                programId = patron.ProgID.ToString();
                MyAvatarPrint.Text = Tools.DisplayHelper.FormatName(patron.FirstName,
                    patron.LastName,
                    patron.Username);
            }
            else
            {
                MyAvatarPrint.Text = "My Avatar";
            }

            if (string.IsNullOrEmpty(programId))
            {
                var sessionProgId = Session["ProgramId"];
                if (sessionProgId != null)
                {
                    programId = sessionProgId.ToString();
                }
            }

            if (string.IsNullOrEmpty(programId))
            {
                try
                {
                    programId = DAL.Programs.GetDefaultProgramID().ToString();
                }
                catch (Exception) { }
            }

            string bannerPath = new Logic.Banner().FullMetadataBannerPath(
                WebTools.GetBaseUrl(Request),
                programId,
                Server);

            if (!string.IsNullOrEmpty(bannerPath))
            {
                BannerImagePrint.ImageUrl = bannerPath;
            }
            else
            {
                BannerImagePrint.Visible = false;
            }

            string avatarPath = null;
            string avatarMdPath = null;
            bool validAvatar = false;
            string avatarId = Request.QueryString["AvatarId"];
            if (!string.IsNullOrEmpty(avatarId) && avatarId.Length <= 24)
            {
                char[] avatarIdArray = avatarId.ToCharArray();

                avatarIdArray = Array.FindAll<char>(avatarIdArray,
                    (c => (char.IsLetterOrDigit(c))));
                avatarId = new string(avatarIdArray);

                avatarPath = string.Format("~/Images/AvatarCache/{0}.png", avatarId);
                avatarMdPath = string.Format("~/Images/AvatarCache/md_{0}.png", avatarId);

                if (File.Exists(Server.MapPath(avatarPath)))
                {
                    validAvatar = true;
                    AvatarImage.ImageUrl = AvatarImagePrint.ImageUrl = avatarPath;
                    AvatarPanel.Visible = true;
                }
            }

            if (!validAvatar)
            {
                AvatarPanel.Visible = false;
            }
            else
            {
                // begin social
                var wt = new WebTools();

                var fbDescription = StringResources.getStringOrNull("facebook-description");
                var hashtags = StringResources.getStringOrNull("socialmedia-hashtags");

                var title = string.Format("{0} avatar", SystemName.Text);
                var description = string.Format("Check out this awesome avatar in {0}!",
                    SystemName.Text);

                var baseUrl = WebTools.GetBaseUrl(Request);
                var avatarDetailPath = string.Format("{0}/Avatar/View.aspx?AvatarId={1}",
                    baseUrl,
                    avatarId);
                var fullAvatarPath = string.Format("{0}{1}",
                    baseUrl,
                    VirtualPathUtility.ToAbsolute(avatarPath));
                var fullAvatarMdPath = string.Format("{0}{1}",
                    baseUrl,
                    VirtualPathUtility.ToAbsolute(avatarMdPath));

                if (patron != null)
                {
                    title = string.Format("My {0} avatar", SystemName.Text);
                    description = string.Format("Check out my awesome avatar in {0}!",
                        SystemName.Text);
                }

                wt.AddOgMetadata(Metadata,
                    title,
                    wt.BuildFacebookDescription(description, hashtags, fbDescription),
                    fullAvatarPath,
                    avatarDetailPath,
                    facebookApp: StringResources.getString("facebook-appid"));

                wt.AddTwitterMetadata(Metadata,
                    title,
                    description,
                    fullAvatarMdPath,
                    StringResources.getString("twitter-username"));

                TwitterShare.NavigateUrl = wt.GetTwitterLink(description,
                    Server.UrlEncode(avatarDetailPath),
                    hashtags);
                TwitterShare.Visible = true;

                FacebookShare.NavigateUrl = wt.GetFacebookLink(Server.UrlEncode(avatarDetailPath));
                FacebookShare.Visible = true;
                // end social
            }

            AvatarPrintPanel.Visible = AvatarPanel.Visible;
            AvatarAlert.Visible = !AvatarPanel.Visible;
        }