/// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            int id = await AdData.GetAdId();
            HelperMethods.CreateSingleAdUnit(id, "TallAd", AdGrid);
            HelperMethods.CreateAdUnits(id, "TallAd", AdGrid2, 5);

            // Retrieve Json data, and load the roles and set up background toast (one time process)
            var roles = await DataSource.GetRolesAsync();
            var rolesWithSearch = new ObservableCollection<Role>(roles);
            rolesWithSearch.Insert(0, new Role("Search"));
            this.DefaultViewModel["Roles"] = rolesWithSearch;

            // Toast background task setup 
            if (e.PageState == null || (bool)e.PageState["firstLoad"] == true)
            {
                CheckAppVersion();
                string version = localSettings.Values["AppVersion"] as string;

                // Only show imminent toasts up to 2 times that the app is launched 
                if (localSettings.Values[version] == null)
                    localSettings.Values[version] = 0;

                if ((int)localSettings.Values[version] < 2)
                {
                    setupFeatureToast(); // Flashes a new feature message 
                    setupReuseToast(); // Creates a message indicating user to reuse app after 30 minutes of opening
                    localSettings.Values[version] = 1 + (int)localSettings.Values[version];
                }
                await setupToast();  // Background toast in 72 hours talking about new champion data
            }

        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // Check for internet connection
            App.IsInternetAvailable();

            int id = await AdData.GetAdId();
            int count = MemoryManager.AppMemoryUsageLimit / (1024 * 1024) > 700 ? 55 : 40;
            HelperMethods.CreateSingleAdUnit(id, "HorizontalAdSmall", AdGrid);
            HelperMethods.CreateAdUnits(id, "HorizontalAdSmall", AdGrid2, count);

            // Load all the roles (which contains all the champions) from the json file 
            var roles = StatsDataSource.GetRoles();
            this.DefaultViewModel["Roles"] = roles;
            await StatsDataSource.GetChampionsAsync();

            // Toast background task setup 
            if (e.PageState == null || (bool)e.PageState["firstLoad"] == true)
            {
                CheckAppVersion();
                string version = localSettings.Values["AppVersion"] as string;

                // Only show imminent toasts up to 5 times that the app is launched 
                if (localSettings.Values[version] == null)
                    localSettings.Values[version] = 0;

                if ((int)localSettings.Values[version] < 5)
                {
                    setupFeatureToast(); // Flashes a new feature message 
                    setupReuseToast(50); // Creates a message indicating user to reuse app after 50 minutes of opening
                    setupReuseToast(50*8); // Creates a message indicating user to reuse app after 8 hours of opening
                    localSettings.Values[version] = 1 + (int)localSettings.Values[version];
                }
                await setupToast();  // Background toast in 50 hours talking about new champion data
            }
        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)  //e is the unique ID
        {
            App.IsInternetAvailable();

            int id = await AdData.GetAdId();
            int count = MemoryManager.AppMemoryUsageLimit / (1024 * 1024) > 700 ? 55 : 40;
            HelperMethods.CreateSingleAdUnit(id, "HorizontalAdSmall", AdGrid);
            HelperMethods.CreateAdUnits(id, "HorizontalAdSmall", AdGrid2, count);

            reviewApp();

            // Set up champion data 
            champions = await StatsDataSource.GetChampionsAsync();
            if (champions == null) {
                MessageDialog messageBox = new MessageDialog("Make sure your internet connection is working and try again!");
                await messageBox.ShowAsync();
                Application.Current.Exit();
            }

            var GroupedChampions = champions.ChampionInfos.ToAlphaGroups(x => x.Value.Name); 
            DefaultViewModel["GroupedChampions"] = GroupedChampions;

            // Set up roles
            string selectedRole = (string)e.NavigationParameter;
            DefaultViewModel["Roles"] = StatsDataSource.GetRoles(); 
            DefaultViewModel["SelectedRole"] = selectedRole;


            // Configure view to either 'All' or filtered role
            if (selectedRole != "All")
            {
                // Do a null check incase of race condition with UI, and raise a flag incase UI hasn't loaded yet for its load to set visibility
                isInitialAllView = false;
                if (JumpList != null)
                {
                    JumpList.Visibility = Visibility.Collapsed;
                }

                DefaultViewModel["Filter"] = champions.ChampionInfos.Where(x => x.Value.Tags[0] == selectedRole).OrderBy(x => x.Value.Name);

                if (FilterGridView != null)
                {
                    FilterGridView.Visibility = Visibility.Visible;
                }
            }
        }
        /// <summary>
        /// Populates the page with content passed during navigation. Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>.
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            App.IsInternetAvailable();

            int id = await AdData.GetAdId();
            int count = MemoryManager.AppMemoryUsageLimit / (1024 * 1024) > 700 ? 55 : 40;
            HelperMethods.CreateSingleAdUnit(id, "HorizontalAdSmall", AdGrid);
            HelperMethods.CreateAdUnits(id, "HorizontalAdSmall", AdGrid2, count);

            // Setup the underlying UI 
            string champKey = (string)e.NavigationParameter;
            champions = await StatsDataSource.GetChampionsAsync();
       
            // Could be passed either the key or name, check for either case
            champInfo = champions.ChampionInfos.Where(x => x.Key == champKey).FirstOrDefault().Value;
            if (champInfo == null)
                champInfo = champions.ChampionInfos.Values.Where(x => x.Name == champKey).FirstOrDefault();

            this.DefaultViewModel["Champion"] = champInfo;
            this.DefaultViewModel["Filter"] = champions.ChampionInfos.OrderBy(x => x.Value.Name);


            // If navigating via a counterpick, on loading that page, remove the previous history so the back page will go to main or role, not champion
            var prevPage = Frame.BackStack.ElementAt(Frame.BackStackDepth - 1);
            if (prevPage.SourcePageType.Equals(typeof(ChampionPage)))
            {
                Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1);
            }

            // Grab the champion feedback from the server 
            await commentViewModel.GetChampionFeedbackAsync(champInfo.Name);

            // Check if an there was no champion retrieved as well as an error message (must be internet connection problem)
            if (commentViewModel.ChampionFeedback == null){
                MessageDialog messageBox = new MessageDialog("Make sure your internet connection is working and try again!");
                await messageBox.ShowAsync();
                Application.Current.Exit();
            }
           
            // Collapse the progress ring once counters have been loaded assuming the textboxes load first
            DefaultViewModel["LoadingVisibility"] = Visibility.Collapsed;

            // Make updates to champion comments observable
            this.DefaultViewModel["ChampionFeedback"] = commentViewModel.ChampionFeedback;
        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)  //e is the unique ID
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data.
            var roleId = e.NavigationParameter as string;           //3 Scenarios, filter, all, or role 

            if (roleId == null)        //Filter case
            {
                var filter = e.NavigationParameter as Role;
                DefaultViewModel["Role"] = filter;
            }
            else      //All or role case 
            {
                var role = DataSource.GetRole(roleId);

                if (role.Champions.Count == 0)     //ONE TIME LOAD ALL ONLY (role Case)
                    role = DataSource.GetAllChampions();

                DefaultViewModel["Role"] = role;
            }
        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // Check for internet connection
            App.IsInternetAvailable();

            int id = await AdData.GetAdId();
            int count = MemoryManager.AppMemoryUsageLimit / (1024 * 1024) > 700 ? 30 : 20;
            HelperMethods.CreateSingleAdUnit(id, "HorizontalAdSmall", AdGrid);
            HelperMethods.CreateAdUnits(id, "HorizontalAdSmall", AdGrid2, count);

            string champKey = e.NavigationParameter as string;
            var championData = await StatsDataSource.GetCounterStatsAsync(champKey);
            var champions = await StatsDataSource.GetChampionsAsync();
            var patch = champions.Version;
            patch = Regex.Match(patch, @"\d\.\d+").Value;  // Format patch from (x.xx.x to x.xx)

            DefaultViewModel["ChampionData"] = championData;
            DefaultViewModel["ChampionInfo"] = champions.ChampionInfos.Where(x => x.Key == champKey).FirstOrDefault().Value;
            DefaultViewModel["Patch"] = patch;
            DefaultViewModel["LoadingVisibility"] = Visibility.Collapsed;
        }
        /// <summary>
        /// Populates the page with content passed during navigation. Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>.
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var championId = (string)e.NavigationParameter;
            var champion = DataSource.GetChampion(championId);
            this.DefaultViewModel["Champion"] = champion;
            this.DefaultViewModel["Role"] = DataSource.GetRoleId(champion.UniqueId);

            var ChampList = new List<Image>();
            var StackList = new List<StackPanel>();
            ChampList.Add(Champ1); ChampList.Add(Champ2); ChampList.Add(Champ3); ChampList.Add(Champ4); ChampList.Add(Champ5);
            StackList.Add(Stack1);StackList.Add(Stack2);StackList.Add(Stack3);StackList.Add(Stack4);StackList.Add(Stack5);
            //var champlist = new Image[5];
            //champlist[0] = Champ1; champlist[1] = Champ2; champlist[2] = Champ3; champlist[3] = Champ4; champlist[4] = Champ5;

            int i = 0;
            foreach (var counter in champion.Counters){
                var uri = "ms-appx:///Assets/" + counter + "_Square_0.png";
                ChampList[i].Source = new BitmapImage(new Uri(uri, UriKind.Absolute));
                int f = i;
                while (f != 5){
                    Image image = new Image(); ;
                    image.Source = new BitmapImage(new Uri("ms-appx:///Assets/Short_Fuse.jpg", UriKind.Absolute));
                    StackList[i].Children.Add(image);       //Recall that nothing is saved, so when viewing again, it'll be a fresh stacklist
                    f++;
                }
                int d = i;
                while (d != 0)
                {
                    Image image = new Image(); ;
                    image.Source = new BitmapImage(new Uri("ms-appx:///Assets/Short_Fuse.jpg", UriKind.Absolute));
                    StackList[i].Children.Add(image);
                    image.Opacity = 0.2;
                    d--;
                }
                i++;
            }
            
        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)  //e is the unique ID
        {
            int id = await AdData.GetAdId();
            HelperMethods.CreateSingleAdUnit(id, "TallAd", AdGrid);
            HelperMethods.CreateAdUnits(id, "TallAd", AdGrid2, 5);

            ReviewApp();

            string roleId;
            navigationRole = e.NavigationParameter as string;
            // If navigating from main page, use that role selected, otherwise use the saved role prior to navigating to champion page
            if (e.PageState == null || navigationRole != (string)e.PageState["NavigationRole"])
            {
                roleId = navigationRole;
            }
            else
            {
                roleId = (string)e.PageState["savedRoleId"];
            }

            roles = await DataSource.GetRolesAsync();  // Gets a reference to all the roles -- no data is seralized again (already done on bootup)
            var allRole = roles[0]; // Gets the all role 
            var GroupedChampions = JumpListHelper.ToAlphaGroups(allRole.Champions, x => x.UniqueId); //Group them to alphabetical headers and remove the first 2 (don't need numbers)
            GroupedChampions.RemoveRange(0, 2);
            allRole.GroupedChampions.Source = GroupedChampions;
            DefaultViewModel["Roles"] = roles;

            // Smoothes out the loading process to get to desired page immedaitely 
            if (roleId == "Filter")
            {
                sectionIndex = MainHub.Sections.Count() - 1;
            }
            else
            {
                sectionIndex = roles.IndexOf(DataSource.GetRole(roleId));
            }

            MainHub.DefaultSectionIndex = sectionIndex;
        }
        /// <summary>
        /// Populates the page with content passed during navigation. Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>.
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            int id = await AdData.GetAdId();
            HelperMethods.CreateSingleAdUnit(id,"TallAd", AdGrid);
            HelperMethods.CreateAdUnits(id, "TallAd", AdGrid2, 5);

            // Setup the underlying UI 
            var champName = (string)e.NavigationParameter;
            Champion champion = DataSource.GetChampion(champName);
            champions = DataSource.GetAllChampions();
            this.DefaultViewModel["Champion"] = champion;
            this.DefaultViewModel["Role"] = DataSource.GetRoleId(champion.UniqueId);
            this.DefaultViewModel["Filter"] = champions.Champions;

            
            // If navigating via a counterpick, on loading that page, remove the previous history so the back page will go to main or role, not champion
            var prevPage = Frame.BackStack.ElementAt(Frame.BackStackDepth - 1);
            if (prevPage.SourcePageType.Equals(typeof(ChampionPage))){
                Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1);
            }

            // Champion feedback code 
            // await commentViewModel.SeedDataAsync(champions);
            // Grab the champion feedback from the server 
            await commentViewModel.GetChampionFeedbackAsync(champName);

            // Check if an there was no champion retrieved as well as an error message (must be internet connection problem)
            if (commentViewModel.ChampionFeedback == null && commentViewModel.ErrorMessage != null){
                MessageDialog messageBox = new MessageDialog("Make sure your internet connection is working and try again!");
                await messageBox.ShowAsync();
                Application.Current.Exit();
            }

           
            // Collapse the progress ring once counters have been loaded. If the ring hasn't loaded yet, set a boolean to collapse it once it loads.
            championFeedbackLoaded = true;

            if (counterLoadingRing != null)
                counterLoadingRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            if (easyMatchupLoadingRing != null)
                easyMatchupLoadingRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            if (synergyLoadingRing != null)
                synergyLoadingRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            if (counterCommentsLoadingRing != null)
                counterCommentsLoadingRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            if (playingCommentsLoadingRing != null)
                playingCommentsLoadingRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

            // Check if comments exist for counter comments. If not, show a message indicating so. 
            if (commentViewModel.ChampionFeedback.Comments.Where(x => x.Page == PageEnum.CommentPage.Counter).Count() == 0) {
                if (counterMessage == null) 
                    emptyComments = true;
                else 
                    counterMessage.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }

            // Check if comments exist for playing comments. If not, show a message indicating so. 
            if (commentViewModel.ChampionFeedback.Comments.Where(x => x.Page == PageEnum.CommentPage.Playing).Count() == 0)
            {
                if (playingMessage == null)
                    emptyPlayingComments = true;
                else 
                    playingMessage.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }

            // Check if synergy champions existing. If not, show a message indicating so. 
            if (commentViewModel.ChampionFeedback.Counters.Where(x => x.Page == PageEnum.ChampionPage.Synergy).Count() == 0)
            {
                if (synergyMessage == null)
                    emptySynergyChampions = true;
                else
                    synergyMessage.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }

            // Make updates to champion comments observable
            this.DefaultViewModel["ChampionFeedback"] = commentViewModel.ChampionFeedback;
        }
 /// <summary>
 /// Populates the page with content passed during navigation.  Any saved state is also
 /// provided when recreating a page from a prior session.
 /// </summary>
 /// <param name="sender">
 /// The source of the event; typically <see cref="NavigationHelper"/>
 /// </param>
 /// <param name="e">Event data that provides both the navigation parameter passed to
 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
 /// a dictionary of state preserved by this page during an earlier
 /// session.  The state will be null the first time a page is visited.</param>
 private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
 {
 }
        /// <summary>
        /// Populates the page with content passed during navigation. Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>.
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            reviewApp();
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            //If navigating via a counterpick, on loading that page, remove the previous history so the back page will go to main or role, not champion
            var prevPage = Frame.BackStack.ElementAt(Frame.BackStackDepth - 1);
            if (prevPage.SourcePageType.Equals(typeof(ChampionPage)))
            {
                Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1);
                Debug.WriteLine("Done");
            }
            String championId = (string)e.NavigationParameter;
            Champion champion = DataSource.GetChampion(championId);
            this.DefaultViewModel["Champion"] = champion;
            this.DefaultViewModel["Role"] = DataSource.GetRoleId(champion.UniqueId);

            
            ChampList.Add(Champ1); ChampList.Add(Champ2); ChampList.Add(Champ3); ChampList.Add(Champ4); ChampList.Add(Champ5);
            StackList.Add(Stack1);StackList.Add(Stack2);StackList.Add(Stack3);StackList.Add(Stack4);StackList.Add(Stack5);
            //var champlist = new Image[5];
            //champlist[0] = Champ1; champlist[1] = Champ2; champlist[2] = Champ3; champlist[3] = Champ4; champlist[4] = Champ5;

            int i = 0;
            counters = champion.Counters;
            foreach (var counter in counters){
                var uri = "ms-appx:///Assets/" + counter + "_Square_0.png";
                ChampList[i].Source = new BitmapImage(new Uri(uri, UriKind.Absolute));
                int f = i;
                while (f != 5){
                    Image image = new Image(); ;
                    image.Source = new BitmapImage(new Uri("ms-appx:///Assets/Short_Fuse.jpg", UriKind.Absolute));
                    StackList[i].Children.Add(image);       //Recall that nothing is saved, so when viewing again, it'll be a fresh stacklist
                    f++;
                }
                int d = i;
                while (d != 0)
                {
                    Image image = new Image(); ;
                    image.Source = new BitmapImage(new Uri("ms-appx:///Assets/Short_Fuse.jpg", UriKind.Absolute));
                    StackList[i].Children.Add(image);
                    image.Opacity = 0.2;
                    d--;
                }
                i++;
            }
            
        }
 /// <summary>
 /// Populates the page with content passed during navigation.  Any saved state is also
 /// provided when recreating a page from a prior session.
 /// </summary>
 /// <param name="sender">
 /// The source of the event; typically <see cref="NavigationHelper"/>
 /// </param>
 /// <param name="e">Event data that provides both the navigation parameter passed to
 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
 /// a dictionary of state preserved by this page during an earlier
 /// session.  The state will be null the first time a page is visited.</param>
 private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
 {
     // TODO: Create an appropriate data model for your problem domain to replace the sample data
     var roles = await DataSource.GetRolesAsync() ;     //On loading the hub page, add all the groups to the default view model
     this.DefaultViewModel["Roles"] = roles;     //Which in turn is the data context for the hub page, with only one thing as a whole in it
 }