/// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
#if WAS
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
#endif
        protected override void LoadState(LoadStateEventArgs e) // WAS: LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            string navigationParameter = e.NavigationParameter.ToString();
            var pageState = e.PageState;
            // navigationParameter will be timestamp of form: 2012-08-13 18:03:26 -04:00
            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
            {
                navigationParameter = pageState["SelectedItem"].ToString();
            }

            // was, but didn't handle fact that same item can appear in multiple groups:
            // var group = SampleDataSource.GetGroupFromItem(navigationParameter.ToString());
            var group = SampleDataSource.GetGroup(App.CurrentSearchResultsGroupName);

            // Assigned:
            //   - a bindable group to this.DefaultViewModel["Group"]
            //   - a collection of bindable items to this.DefaultViewModel["Items"]
            //   - the selected item to this.flipView.SelectedItem
            //var group = SampleDataSource.GetGroup((String)"AllStations");
            this.DefaultViewModel["Group"] = group;
            this.DefaultViewModel["Items"] = group.Items;
            //SampleDataItem sdi = new SampleDataItem();
            //sdi.UniqueId = (String)navigationParameter;
            String id = (String)navigationParameter;
            //this.flipView.SelectedItem = id; //sdi.UniqueId;
            this.flipView.SelectedItem = SampleDataSource.GetItem(id, App.CurrentSearchResultsGroupName);

        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        protected override async void LoadState(LoadStateEventArgs e)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var navigationParameter = e.NavigationParameter;
            var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter);
            this.DefaultViewModel["Items"] = sampleDataGroups;

            // Too simple events model:
            // 2nd try: TP_EventsDataList edl = new TP_EventsDataList();
            if (App.DelayedMessageToUserOnStartup != "") // Got content during App.OnLaunched, but can't be easily shown until now
            {
                MessageDialog dlg = new MessageDialog(App.DelayedMessageToUserOnStartup);
                await dlg.ShowAsync();
                App.DelayedMessageToUserOnStartup = "";
            }
            App.AppFinishedLaunching = true; // set to true during home page launch
            // Not needed: base.LoadState(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="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(LoadStateEventArgs e) // was: protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) // Glenn changes to async
        {
            string navigationParameter = e.NavigationParameter.ToString();
            var pageState = e.PageState;
            SampleDataGroup group = SampleDataSource.GetGroup(navigationParameter);
            this.DefaultViewModel["Group"] = group;
            this.DefaultViewModel["Items"] = group.Items;

            // Dunno if this is a good idea, but need to get group for sort flyout:
            App.CurrentSearchResultsGroupName =(String)navigationParameter;
            App.MyAssert(App.CurrentSearchResultsGroupName == "Outbox" || App.CurrentSearchResultsGroupName == "AllStations");
            isOutbox = (bool)(App.CurrentSearchResultsGroupName == "Outbox");

            if (isOutbox)
                await LoadStateOutbox();
            else
                await LoadStateAllStations();

            if (pageState == null)
            {
                this.itemListView.SelectedItem = null;
                // When this is a new page, select the first item automatically unless logical page
                // navigation is being used (see the logical page navigation #region below.)
                if (!this.UsingLogicalPageNavigation() && this.itemsViewSource.View != null)
                {
                    this.itemsViewSource.View.MoveCurrentToFirst();
                }
            }
            else
            {
                // Restore the previously saved state associated with this page
                if (pageState.ContainsKey("SelectedItem") && this.itemsViewSource.View != null)
                {
                    var selectedItem = SampleDataSource.GetItem((String)pageState["SelectedItem"]);
                    if (!this.itemsViewSource.View.MoveCurrentTo(selectedItem)) // may fail if selected item was deleted elsewhere
                        this.itemsViewSource.View.MoveCurrentToFirst(); // New Aug 2015, Release 6 (v 3.6)
                }
            }

            //dt = new DispatcherTimer();
            //dt.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1000 milliseconds
            //dt.Tick += dt_TickRefreshView;
            //dt.Start();
        }
        /// <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="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(LoadStateEventArgs e) // WAS: LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            Opened();
#if TODOish
            pageSubtitle.Text = " " + App.CurrentDisasterEventName; // TO DO: binding in XAML instead of here?  Add space to separate from icon
            string prefix = "ms-appx:///";
            if (App.CurrentDisasterEventTypeIcon.Length > prefix.Length)
            {
                eventTypeImage.Source = new BitmapImage(new Uri(App.CurrentDisasterEventTypeIcon));
#if MAYBE
                string path = App.CurrentDisasterEventTypeIcon.Substring(prefix.Length);
                path += Windows.ApplicationModel.Package.Current.InstalledLocation.ToString();
                BitmapImage img = new BitmapImage();
                var uri = new Uri(path);
                img.UriSource = uri;
                eventTypeImage.Source = img;
#endif
                // Tried XAML binding, didn't work:                 <Image x:Name="eventTypeImage" Source="{Binding CurrentDisasterEventTypeIcon}" Width="40" VerticalAlignment="Top"/>
                MyZoneButtonItemWidth = "140";
            }
#endif
        }
        /// <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="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override async void LoadState(LoadStateEventArgs e) // WAS: LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            string navigationParameter = e.NavigationParameter.ToString();
            var pageState = e.PageState;

            //Ignore App.CurrentDisaster.EventName;
            App.SearchResultsEventTitleTextBasedOnCurrentFilterProfile = eventText.Text = GetEventTextBasedOnCurrentFilterProfile();
            // exclude Org from App.SearchResultsEventTitleTextBasedOnCurrentFilterProfile, to ease interrogating string elsewhere
            if (App.CurrentFilterProfile.ReportedAtMyOrgOnly)
                eventText.Text += ", " + App.CurrentOrgContactInfo.OrgAbbrOrShortName;
            else
                eventText.Text += ", Any Org";
            App.CurrentSearchQuery = navigationParameter as String;
            //App.PatientDataGroups.ReFilter(); // filter or query has changed.  This will affect contents of groups fetched below.
            await App.PatientDataGroups.ReSortAndFilter(); // await added v 3.5
            await SampleDataSource.RefreshOutboxAndAllStationsItems(); // Propagate here. Await added for v 3.5
            var gOut = SampleDataSource.GetGroup("Outbox");
            var gAll = SampleDataSource.GetGroup("AllStations");

            var query = App.CurrentSearchQuery == null ? string.Empty : App.CurrentSearchQuery.ToLower();

            //       Only the first filter, typically "All", should pass true as a third argument in
            //       order to start in an active state.  Results for the active filter are provided
            //       in Filter_SelectionChanged below.

            if (String.IsNullOrEmpty(App.CurrentSearchResultsGroupName)) // Glenn adds this, maybe can add to data model at some point
                App.CurrentSearchResultsGroupName = "Outbox";

            var filterList = new List<Filter>();
            if (App.CurrentSearchResultsGroupName == "Outbox")
            {
                filterList.Add(new Filter("📮  Outbox", GetSearchResultList(gOut, query).Count, true));
                filterList.Add(new Filter("👪  All Stations", GetSearchResultList(gAll, query).Count, false)); //AllStations was FullSearch earlier
            }
            else
            {
                // Keep the filter order unchanged, so UI doesn't swap them.
                filterList.Add(new Filter("📮  Outbox", GetSearchResultList(gOut, query).Count, false));
                filterList.Add(new Filter("👪  All Stations", GetSearchResultList(gAll, query).Count, true));
            }

            /* Compare with SplitPage:
            var group = SampleDataSource.GetGroup((String)navigationParameter);
            this.DefaultViewModel["Group"] = group;
            this.DefaultViewModel["Items"] = group.Items; */
 
            var group = SampleDataSource.GetGroup(App.CurrentSearchResultsGroupName);
            this.DefaultViewModel["Group"] = group;

            /* Maybe not:
            this.DefaultViewModel["Items"] = group.Items; */

            string filteron = "";
            if(App.CurrentFilterProfile.HasFlyoutFilteringOtherThanEvent()) //was: if(App.PatientDataGroups.HasFlyoutFiltering())
                filteron = "Filtered";
            otherFilterText.Text = filteron;

            // Communicate results through the view model
            AdjustQueryText(); // broken out June 2015
            this.DefaultViewModel["Filters"] = filterList;  // These are the group names
            this.DefaultViewModel["ShowFilters"] = filterList.Count > 1;
/* orig template:
            var queryText = navigationParameter as String;

            // TODO: Application-specific searching logic.  The search process is responsible for
            //       creating a list of user-selectable result categories:
            //
            //       filterList.Add(new Filter("<filter name>", <result count>));
            //
            //       Only the first filter, typically "All", should pass true as a third argument in
            //       order to start in an active state.  Results for the active filter are provided
            //       in Filter_SelectionChanged below.

            var filterList = new List<Filter>();
            filterList.Add(new Filter("All", 0, true));

            // Communicate results through the view model
            this.DefaultViewModel["QueryText"] = '\u201c' + queryText + '\u201d';
            this.DefaultViewModel["Filters"] = filterList;
            this.DefaultViewModel["ShowFilters"] = filterList.Count > 1; */
        }
        private async void sortFlyout_Tapped(object sender, RoutedEventArgs e) // before June 2015 was sortFlyout_Click
        {
            // WAS: if(App.CurrentVisualState == "vs320Wide") // WAS: if (ApplicationView.Value == ApplicationViewState.Snapped)
            // Workaround for iPopup not seeming to work with non-full-screen modes
            if (App.CurrentVisualState != "FullScreenLandscape" && App.CurrentVisualState != "FullScreenPortrait")
            // equivalent: if(App.CurrentVisualState == "vs320Wide" || App.CurrentVisualState == "vs321To500Wide" || App.CurrentVisualState == "vs501To672Wide" || App.CurrentVisualState == "vs673To1025Wide" || App.CurrentVisualState == "vs1026To1365Wide" || App.CurrentVisualState == "vsOver1365Wide")
            {
                this.Frame.Navigate(typeof(SortNonFlyout), "pageSortNonFlyout");
                // may set to true: App.CurrentFilterProfile.AControlChanged
            }
            else
            {
                //Windows.UI.ViewManagement.ApplicationView.TryUnsnap();// Glenn's quick hack, since this doesn't work well while snapped
                var flyout = new SortFlyout.sFlyout();
                // we could introduce our own variable here, but we'll reuse filter's

                App.CurrentFilterProfile.AControlChanged = await flyout.ShowAsync();
            }
            if (App.CurrentFilterProfile.AControlChanged)
            {
                //GroupOrFlyoutFilterChanged(); // Search is not refreshed until flyout is dismissed.  Simple but maybe not ideal.
                LoadStateEventArgs lsea = new LoadStateEventArgs((Object)App.CurrentSearchQuery, null); // As if navigating anew to this page... to get lists & their counts right
                LoadState(lsea);
                // WAS: LoadState((Object)App.CurrentSearchQuery, null); // As if navigating anew to this page... to get lists & their counts right
                App.CurrentFilterProfile.AControlChanged = false;
            }
        }
 private async void filterFlyout_Tapped(object sender, RoutedEventArgs e) // before June 2015 was filterFlyout_Click
 {
     // was: if (App.CurrentVisualState == "vs320Wide") // WAS: if (ApplicationView.Value == ApplicationViewState.Snapped)
     // Workaround for iPopup not seeming to work with non-full-screen modes
     if (App.CurrentVisualState != "FullScreenLandscape" && App.CurrentVisualState != "FullScreenPortrait")
         // equivalent: if(App.CurrentVisualState == "vs320Wide" || App.CurrentVisualState == "vs321To500Wide" || App.CurrentVisualState == "vs501To672Wide" || App.CurrentVisualState == "vs673To1025Wide" || App.CurrentVisualState == "vs1026To1365Wide" || App.CurrentVisualState == "vsOver1365Wide")
     {
         this.Frame.Navigate(typeof(FilterNonFlyout), "pageFilterNonFlyout");
         // may set to true: App.CurrentFilterProfile.AControlChanged
     }
     else
     {
         //Windows.UI.ViewManagement.ApplicationView.TryUnsnap();// Glenn's quick hack, since this doesn't work well while snapped
         // Instead, each click on button creates an instance, but they just pile up until the user unsnaps, then they appear atop each other
         var flyout = new FilterFlyout.Flyout();
         App.CurrentFilterProfile.AControlChanged = await flyout.ShowAsync();
     }
     if (App.CurrentFilterProfile.AControlChanged)
     {
         //GroupOrFlyoutFilterChanged(); // Search is not refreshed until flyout is dismissed.  Simple but maybe not ideal.
         LoadStateEventArgs lsea = new LoadStateEventArgs((Object)App.CurrentSearchQuery, null); // As if navigating anew to this page... to get lists & their counts right
         LoadState(lsea);
         //WAS: LoadState((Object)App.CurrentSearchQuery, null); // As if navigating anew to this page... to get lists & their counts right
         App.CurrentFilterProfile.AControlChanged = false;
         // Persist the change...
         App.FilterProfileList.UpdateOrAdd(App.CurrentFilterProfile);
         await App.FilterProfileList.WriteXML();
     }
 }
        private void CheckBoxMyOrgOnly_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (isOutbox)
            {
                App.OutboxCheckBoxMyOrgOnly = (bool)((CheckBox)sender).IsChecked;
//                if (((CheckBox)sender).Name == "CheckBoxMyOrgOnly") // propagate from control visible in current view mode to hidden control
//                    CheckBoxMyOrgOnlyPortrait.IsChecked = App.OutboxCheckBoxMyOrgOnly;
//                else
                    CheckBoxMyOrgOnly.IsChecked = App.OutboxCheckBoxMyOrgOnly;
                SetOutboxEventAndOrgText();
            }
            else
            {

                App.AllStationsCheckBoxMyOrgOnly = (bool)((CheckBox)sender).IsChecked;
//                if (((CheckBox)sender).Name == "CheckBoxMyOrgOnly") // propagate from control visible in current view mode to hidden control
//                    CheckBoxMyOrgOnlyPortrait.IsChecked = App.AllStationsCheckBoxMyOrgOnly;
//                else
                    CheckBoxMyOrgOnly.IsChecked = App.AllStationsCheckBoxMyOrgOnly;
                SetAllStationsEventAndOrgText();
            }
            LoadStateEventArgs lsea = new LoadStateEventArgs(App.CurrentSearchResultsGroupName, null);
            LoadState(lsea);
            //was: LoadState(App.CurrentSearchResultsGroupName, null);
        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        protected override void LoadState(LoadStateEventArgs e)
        {
            InitiateZones();
            // was before Release 2:
            // if (!String.IsNullOrEmpty(App.CurrentPatient.Zone)) // This test may need refinement
            //    LoadReportFieldsFromObject(pr);
            if (latestNavigation.NavigationMode == NavigationMode.Back) // probably back from webcam
            {
                // Assume there's content to reload
                pr = App.CurrentPatient;
                LoadReportFieldsFromObject(pr);
            }
            pageSubtitle.Text = " " + App.CurrentDisaster.EventName; // TO DO: binding in XAML instead of here?  Add space to separate from icon
            if (App.CurrentDisaster.TypeIconUri.Length > EMBEDDED_FILE_PREFIX.Length)
            {
                eventTypeImage.Source = new BitmapImage(new Uri(App.CurrentDisaster.TypeIconUri));
                // Tried XAML binding, didn't work:                 <Image x:Name="eventTypeImage" Source="{Binding CurrentDisasterEventTypeIcon}" Width="40" VerticalAlignment="Top"/>
                // WAS before next call added: MyZoneButtonItemWidth = "140";
            }
            AdjustZoneButtonWidth();

            UpdateImageLoad();
            if (firstTime)
            {
                firstTime = false;
                UpdateStoryBoard();
            }
            // Not needed: base.LoadState(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>
        protected override async void LoadState(LoadStateEventArgs e) // Glenn added async here, might not turn out well
        {
            // Differs from NewReport:
            if (e.NavigationParameter.ToString() == "pageViewEditReport")
            {
                // Coming from web cam.  We already have what we need in App.CurrentPatient
                //suppressMarkingAsAltered = false;
                updatedReport = App.CurrentPatient;
                await Load_Entry(updatedReport);
            }
            else
            {   // navigation parameter is the unique Id associated with search results in the the flip view
                //suppressMarkingAsAltered = true;
                ShowTitleAndSentTimeAsUnaltered(); // need this?
                ClearEntryAll(); //ClearEntryExceptPatientID(); // Will need more work when we're reloading state from suspend
                string UniqueID = e.NavigationParameter.ToString();

                bool foundPatient = false;
                foreach (var pr_ in App.PatientDataGroups.GetOutbox())
                {
                    if (pr_.WhenLocalTime == UniqueID)
                    {
                        foundPatient = true;
                        App.CurrentPatient = pr_;
                        updatedReport = pr_;
                        await Load_Entry(updatedReport);
                        break;
                    }
                }
                if (!foundPatient)
                {
                    // was before PLUS v34: App.MyAssert(false);
                    string msg =
                        "Sorry, internal problem: TriagePic can't find this report to edit in the Outbox list.\n" +
                        "Conjecture: due to starting an edit, but leaving and then coming back through search?\n" +
                        "This is a known problem of this release of TriagePic for Windows Store.\n" +
                        "If problem persists, consider editing such reports at the TriageTrak web site.";
                    var dialog1 = new MessageDialog(msg);
                    var t1 = dialog1.ShowAsync(); // Assign to t1 to suppress compiler warning
                    return;
                }
            }
            if (App.ReportAltered)
                ShowTitleAndSentTimeAsAltered();

            pageSubtitle.Text = " " + App.ViewedDisaster.EventName; // App.CurrentDisasterEventName; // TO DO: binding in XAML instead of here?  Add space to separate from icon
            ViewedDisasterEventTypeIcon = App.ViewedDisaster.GetIconUriFromEventType();
            // Momentarily shift focus to notes and caption to force text font to the correct color (either black or gray) for contents
            Notes_GotFocusImpl(); // These don't affect the focus, only the content and font color.
            Notes_LostFocusImpl();
#if SUPERCEDED_RELEASE_7
            Caption_GotFocusImpl(); // These don't affect the focus, only the content and font color.
            Caption_LostFocusImpl();
#endif
#if WIN80_CODE_NO_LONGER_WORKS
            // Didn't work in 8.1, returns false.  Maybe because called from LoadState:
            // bool debug = Notes.Focus(FocusState.Programmatic);
            // This was suggested in forum as solution, but still didn't work:
            bool debug = false;
            await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    debug = Notes.Focus(FocusState.Programmatic); // or maybe .Keyboard
                });
            App.MyAssert(debug);
            GiveCaptionFocus();
            PatientIdTextBox.Focus(FocusState.Programmatic); // Didn't work... and for View/Edit makes more sense to put on Comment aka Notes field
#endif

            // In common with NewReport:
            if (ViewedDisasterEventTypeIcon.Length > EMBEDDED_FILE_PREFIX.Length)
            {
                eventTypeImage.Source = new BitmapImage(new Uri(ViewedDisasterEventTypeIcon));
                // Tried XAML binding, didn't work:                 <Image x:Name="eventTypeImage" Source="{Binding CurrentDisasterEventTypeIcon}" Width="40" VerticalAlignment="Top"/>
                // WAS before next call added: MyZoneButtonItemWidth = "140";
            }
            AdjustZoneButtonWidth();

            UpdateImageLoad();
            //suppressMarkingAsAltered = false;
        }
 protected virtual void LoadState(LoadStateEventArgs e) { }
 private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
 {
     LoadState(e);
 }