/// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    imgLoading.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/proLoading.gif");
                    if (Settings["Configure"] != null && Convert.ToString(Settings["Configure"]).Equals("ConfigureLists"))
                    {
                        imgAd.Src = ResolveUrl("~/images/iphoneAd.png");
                        aqufitEntities entities = new aqufitEntities();
                        if (HttpContext.Current.Items["w"] != null || Request["w"] != null)   // view a specific workouts history
                        {
                            atiWorkoutList.Visible      = true;
                            atiStatsPanel.Visible       = false;
                            atiWorkoutViewer.Visible    = true;
                            atiWorkoutListPanel.Visible = false;
                            long wid = Request["w"] != null?Convert.ToInt64(Request["w"]) : Convert.ToInt64(HttpContext.Current.Items["w"]);

                            txtRouteLink.Text = "http://flexfwd.com/" + ProfileSettings.UserName + "/workout-history/" + wid;
                            Workout workout = entities.UserStreamSet.OfType <Workout>().FirstOrDefault(w => w.Id == wid);
                            // get all the workouts that have the same title
                            Workout[] workouts = entities.UserStreamSet.OfType <Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id && w.WorkoutTypeKey == workout.WorkoutTypeKey && w.Title == workout.Title).ToArray();
                            workoutTabTitle.Text = "&nbsp;" + workout.Title;

                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.getWokoutStreamData(base.ProfileSettings.Id, workout);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiStreamScript.generateStreamDom('" + json + "'); });", true);

                            //atiStreamScript
                        }
                        else
                        {
                            atiProfileImg2.Settings = base.ProfileSettings;
                            if (ProfileSettings != null && ProfileSettings is Group)
                            {
                                RadGrid1.Visible           = false;
                                RadGrid2.Visible           = true;
                                atiWorkoutSelector.Visible = false;
                            }
                            atiWorkoutList.Visible = true;
                            atiStatsPanel.Visible  = false;
                            workoutTabTitle.Text   = "Workout History";
                            atiWorkoutTotals.Cols  = 3;

                            // get number of workouts for each workout type
                            WorkoutType[]        wtypes       = entities.WorkoutType.ToArray();
                            IQueryable <Workout> workoutQuery = entities.UserStreamSet.OfType <Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id);
                            foreach (WorkoutType wt in wtypes)
                            {
                                atiWorkoutTotals.Totals.Add(new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                                {
                                    Name  = wt.Name,
                                    Icon  = wt.Icon,
                                    Total = "" + workoutQuery.Where(w => w.WorkoutTypeKey == wt.Id).Count()
                                });
                            }
                        }
                    }
                    else
                    {
                        // for now if the user is not logged in they can not view stats...
                        if (UserSettings == null)
                        {
                            Response.Redirect(ResolveUrl("~/Login") + "?returnurl=" + Request.Url.ToString(), true);
                            return;
                        }

                        atiWorkoutList.Visible = false;
                        atiStatsPanel.Visible  = true;

                        string requestsUrl = Convert.ToString(Settings["RequestsPage"]);
                        // cache workout types if not already done.
                        // TODO: store this in the application startup

                        // Get all the stream data for the user.
                        // TODO: cache the stream list.
                        long wId = 0;
                        if (HttpContext.Current.Items["w"] != null)
                        {
                            wId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                        }
                        else if (Request["w"] != null)
                        {
                            wId = Convert.ToInt64(Request["w"]);
                        }
                        if (wId == 0)
                        {
                            throw new Exception("No Workout specified");
                        }
                        aqufitEntities entities = new aqufitEntities();
                        Workout        workout  = entities.UserStreamSet.OfType <Workout>().Include("WOD").Include("WOD.WODType").FirstOrDefault(w => w.Id == wId);
                        atiWorkoutVisualizer.Text = GetFlexEmbed(workout);

                        // Get the 'LONG' list of past workouts (only one time)
                        const int workoutTake = 50;
                        IQueryable <IGrouping <long, Workout> > workoutHistory = entities.UserStreamSet.OfType <Workout>().Include("WOD").OrderByDescending(w => w.Id).Where(w => w.UserSetting.Id == UserSettings.Id && w.WorkoutTypeKey.HasValue).Take(workoutTake).GroupBy(w => w.WorkoutTypeKey.Value);
                        IEnumerable <Workout> workoutHistoryList = new List <Workout>();
                        foreach (IGrouping <long, Workout> wh in workoutHistory)
                        {
                            workoutHistoryList = workoutHistoryList.Concat(wh.AsEnumerable());
                        }
                        hiddenWorkoutHistory.Value = workoutHistoryList.Select(w => new {
                            Title    = w.Title,
                            Id       = w.Id,
                            Type     = w.WorkoutTypeKey,
                            Wod      = (w.WOD != null ? w.WOD.Id : -1),
                            Distance = w.Distance,
                            Score    = w.Score,
                            Max      = w.Max,
                            Duration = w.Duration
                        }).OrderBy(w => w.Title).ToArray().ToJson();

                        LoadFlexDataForWorkout(workout, Utils.ConstsUtil.GraphContext.DEFAULT);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    imgLoading.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/proLoading.gif");
                    if (Settings["Configure"] != null && Convert.ToString( Settings["Configure"] ).Equals("ConfigureLists") )
                    {
                        imgAd.Src = ResolveUrl("~/images/iphoneAd.png");
                        aqufitEntities entities = new aqufitEntities();
                        if (HttpContext.Current.Items["w"] != null || Request["w"] != null)   // view a specific workouts history
                        {
                            atiWorkoutList.Visible = true;
                            atiStatsPanel.Visible = false;
                            atiWorkoutViewer.Visible = true;
                            atiWorkoutListPanel.Visible = false;
                            long wid = Request["w"] != null ? Convert.ToInt64(Request["w"]) : Convert.ToInt64(HttpContext.Current.Items["w"]);
                            txtRouteLink.Text = "http://flexfwd.com/"+ ProfileSettings.UserName + "/workout-history/" + wid;
                            Workout workout = entities.UserStreamSet.OfType<Workout>().FirstOrDefault(w => w.Id == wid);
                            // get all the workouts that have the same title
                            Workout[] workouts = entities.UserStreamSet.OfType<Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id && w.WorkoutTypeKey == workout.WorkoutTypeKey && w.Title == workout.Title).ToArray();
                            workoutTabTitle.Text = "&nbsp;" + workout.Title;

                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.getWokoutStreamData(base.ProfileSettings.Id, workout);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiStreamScript.generateStreamDom('" + json + "'); });", true);

                            //atiStreamScript
                        }
                        else
                        {
                            atiProfileImg2.Settings = base.ProfileSettings;
                            if (ProfileSettings != null && ProfileSettings is Group)
                            {
                                RadGrid1.Visible = false;
                                RadGrid2.Visible = true;
                                atiWorkoutSelector.Visible = false;
                            }
                            atiWorkoutList.Visible = true;
                            atiStatsPanel.Visible = false;
                            workoutTabTitle.Text = "Workout History";
                            atiWorkoutTotals.Cols = 3;

                            // get number of workouts for each workout type
                            WorkoutType[] wtypes = entities.WorkoutType.ToArray();
                            IQueryable<Workout> workoutQuery = entities.UserStreamSet.OfType<Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id);
                            foreach (WorkoutType wt in wtypes)
                            {
                                atiWorkoutTotals.Totals.Add(new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                                {
                                    Name = wt.Name,
                                    Icon = wt.Icon,
                                    Total = "" + workoutQuery.Where(w => w.WorkoutTypeKey == wt.Id).Count()
                                });
                            }

                        }
                    }
                    else
                    {
                        // for now if the user is not logged in they can not view stats...
                        if (UserSettings == null)
                        {
                            Response.Redirect(ResolveUrl("~/Login") + "?returnurl=" + Request.Url.ToString(), true);
                            return;
                        }

                        atiWorkoutList.Visible = false;
                        atiStatsPanel.Visible = true;

                        string requestsUrl = Convert.ToString(Settings["RequestsPage"]);
                        // cache workout types if not already done.
                        // TODO: store this in the application startup

                        // Get all the stream data for the user.
                        // TODO: cache the stream list.
                        long wId = 0;
                        if (HttpContext.Current.Items["w"] != null)
                        {
                            wId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                        }
                        else if (Request["w"] != null)
                        {
                            wId = Convert.ToInt64(Request["w"]);
                        }
                        if (wId == 0)
                        {
                            throw new Exception("No Workout specified");
                        }
                        aqufitEntities entities = new aqufitEntities();
                        Workout workout = entities.UserStreamSet.OfType<Workout>().Include("WOD").Include("WOD.WODType").FirstOrDefault(w => w.Id == wId);
                        atiWorkoutVisualizer.Text = GetFlexEmbed(workout);

                        // Get the 'LONG' list of past workouts (only one time)
                        const int workoutTake = 50;
                        IQueryable<IGrouping<long, Workout>> workoutHistory = entities.UserStreamSet.OfType<Workout>().Include("WOD").OrderByDescending(w => w.Id).Where(w => w.UserSetting.Id == UserSettings.Id && w.WorkoutTypeKey.HasValue).Take(workoutTake).GroupBy(w => w.WorkoutTypeKey.Value);
                        IEnumerable<Workout> workoutHistoryList = new List<Workout>();
                        foreach (IGrouping<long, Workout> wh in workoutHistory)
                        {
                            workoutHistoryList = workoutHistoryList.Concat(wh.AsEnumerable());
                        }
                        hiddenWorkoutHistory.Value = workoutHistoryList.Select(w => new {
                                                    Title = w.Title,
                                                    Id = w.Id,
                                                    Type = w.WorkoutTypeKey,
                                                    Wod = (w.WOD != null ? w.WOD.Id : -1),
                                                    Distance = w.Distance,
                                                    Score = w.Score,
                                                    Max = w.Max,
                                                    Duration = w.Duration }).OrderBy( w => w.Title).ToArray().ToJson();

                        LoadFlexDataForWorkout(workout, Utils.ConstsUtil.GraphContext.DEFAULT);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }