/// <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)
        {
            user = App.user;
            if (user == null)
                return;

            this.DefaultViewModel["name"] = title.Text = user.Profile.first_name + " " + user.Profile.last_name; // set view model value and title text instantly, for user's real name
            this.DefaultViewModel["avatarSource"] = user.Profile.image_url_75x75;
            this.DefaultViewModel["username"] = user.Profile.login_name;

            this.DefaultViewModel["itemsBought"] = user.Profile.transaction_buy_count;

            this.DefaultViewModel["bio"] = user.Profile.bio;
        }
        /// <summary>
        /// Remove from favorites
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void favoriteButton_Click(object sender, RoutedEventArgs e)
        {
            user = favoriteButton.DataContext as User;
            await FavoritesAccess.RemoveFavoriteUser(user.shop);

            // Remove from the local collection
            foreach(var u in FavoritesAccess.favoriteUsers)
            {
                if(u.user_id == user.user_id)
                {
                    FavoritesAccess.favoriteUsers.Remove(user);
                    break;
                }
            }
        }
        /// <summary>
        /// Get basic user info, profile, receipt & transaction history, addresses
        /// Only works when logged in
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns>User Object</returns>
        public static async Task<User> getUserFull(string user_id)
        {
            string baseURL = App.baseURL;
            HttpClient client = new HttpClient();

            //string parameterKey = "includes", parameterValue = "Profile,BuyerReceipts,BuyerTransactions,Addresses";
            List<Parameter> parameters = new List<Parameter>();
            parameters.Add(new Parameter("includes", "Profile,BuyerReceipts,BuyerTransactions,Addresses"));

            User user = new User();

            if (App.logged_in == false && user_id == "__SELF__")    
            {
                // error if trying to access the logged in user and there is none
                return null;
            }
            else if(App.logged_in == false)     // not logged in
            {
                baseURL = string.Format("{0}/users/{1}", baseURL, user_id);
            }
            else if(App.logged_in == true)      // logged in, supposedly
            {
                baseURL = string.Format("{0}/users/{1}", baseURL, user_id);
                baseURL = AuthenticationAccess.addAuthentication(baseURL, parameters);
            }

            try
            {
                var jsonStream = await client.GetStreamAsync(baseURL);

                using(StreamReader reader = new StreamReader(jsonStream))
                {
                    var serializer = new DataContractJsonSerializer(typeof(Model.User.dataFetch));
                    var container = (Model.User.dataFetch)serializer.ReadObject(jsonStream);    // capture the object that holds the user

                    user = container.results[0];    // only one user requested; get the object at the 0 index
                }
            }
            catch(Exception e)
            {
                App.logged_in = false;      // the user is in fact not logged in
            }

            return user;
        }
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            await loadImageQuality();

            await loadAccessToken();
            if (logged_in == true)
            {
                try
                {
                    user = await FileIO.DeserializeFromFile<User>("user");
                    User tempuser = await UserAccess.getUserFull(userID);       // Check to see if the permission is still granted
                    if (tempuser != null)
                        user = tempuser;    // keep user up to date if possible
                    else
                        App.logged_in = false;
                    // get default address
                    if (user != null)
                        if (user.Addresses != null)
                            foreach (var add in user.Addresses)
                                if (add.is_default_shipping == true)
                                    defaultAddress = add;
                }
                catch(Exception u)
                {
                    string message = u.Message;
                    App.logged_in = false;
                }
            }

            if (defaultAddress == null)
            {
                defaultAddress = new Address();
                defaultAddress.country_id = 209;    // default to US
            }

            checkLicenseState();                    // Check for ad-free purchase

            

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                // TODO: change this value to a cache size that is appropriate for your application
                rootFrame.CacheSize = 1;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
#if WINDOWS_PHONE_APP
                // Removes the turnstile navigation for startup.
                if (rootFrame.ContentTransitions != null)
                {
                    this.transitions = new TransitionCollection();
                    foreach (var c in rootFrame.ContentTransitions)
                    {
                        this.transitions.Add(c);
                    }
                }

                rootFrame.ContentTransitions = null;
                rootFrame.Navigated += this.RootFrame_FirstNavigated;
#endif

                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            // Ensure the current window is active
            Window.Current.Activate();
        }
        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);

            // Hide the ads if the user paid to remove them
            if (App.purchased)
                if(adBottom != null)
                    adBottom.Visibility = Visibility.Collapsed;

            if (App.logged_in)   // change the user options
            {
                user = App.user;
                if(user != null)
                    if(user.Profile != null)
                        this.DefaultViewModel["image_url_75x75"] = user.Profile.image_url_75x75;    // data binding for user image
                try
                {
                    if (avatar != null)
                        if(avatar.Visibility != Visibility.Visible)
                            avatar.Visibility = Visibility.Visible;
                }
                catch(Exception ee)
                {
                    string message = ee.Message;
                }
            }
            else
            {
                if(avatar != null)
                    avatar.Visibility = Visibility.Collapsed;
            }
        }
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);

            if (App.logged_in)   // change the user options
            {
                user = App.user;
                this.DefaultViewModel["image_url_75x75"] = user.Profile.image_url_75x75;    // data binding for user image
                avatar.Visibility = Visibility.Visible;
            }
            else
            {
                avatar.Visibility = Visibility.Collapsed;
            }
        }