/// <summary>
        /// Performs an automatic turn to the first page (cover)
        /// </summary>
        private void TurnToFirstPageAuto()
        {
            // Assign clipping regions and transforms to relevant canvases
            PrevCanvas.Clip                = _oddClipRegion;
            PrevPageCanvas.Clip            = _evenClipRegion;
            PrevPageCanvas.RenderTransform = _transformGroup;
            // Send a message to the ViewModel so it will update the ZIndexes properly
            var ActionMessage = new PageActionMessage()
            {
                action = PageAction.TurningToCover
            };

            Messenger.Default.Send <PageActionMessage>(ActionMessage);
            // Set turning variables accordingly
            _turning   = true;
            _direction = 1;
            _percent   = 1.0;
            TurnTo(_percent);
            _autoTurn = true;
            // Clear menus
            VisualStateManager.GoToState(this, "ClearAll", true);
            _currState  = States.ClearAll;
            _isMenuDown = true;
            // Finish turn, as if we were in the 2nd page (so the previous one will be the 1st)
            _pageIndex = 2;
            CompleteTurn();
        }
        /// <summary>
        /// Performs an automatic turn to the last page (gallery)
        /// </summary>
        private void TurnToLastPageAuto()
        {
            // Assign clipping regions and transforms to relevant canvases
            CurrCanvas.Clip                = _oddClipRegion;
            CurrPageCanvas.Clip            = _evenClipRegion;
            CurrPageCanvas.RenderTransform = _transformGroup;
            // Send a message to the ViewModel so it will update the ZIndexes properly
            var ActionMessage = new PageActionMessage()
            {
                action = PageAction.TurningToGallery
            };

            Messenger.Default.Send <PageActionMessage>(ActionMessage);
            // Set turning variables accordingly
            _turning   = true;
            _direction = -1;
            _percent   = 0.0;
            TurnTo(_percent);
            _autoTurn = true;
            // Clear menus
            VisualStateManager.GoToState(this, "ClearAll", true);
            _currState  = States.ClearAll;
            _isMenuDown = true;
            // Finish turn, as if we were in the previous to last page (so the next one will be the gallery)
            _pageIndex = _totalPages - _duplicatedPages - 1;
            CompleteTurn();
        }
        /// <summary>
        /// Turns a page automatically to the left without any action from the user
        /// </summary>
        private void AutoPageTurn()
        {
            // Set canvases to be modified in the turning effect
            CurrCanvas.Clip                = _oddClipRegion;
            CurrPageCanvas.Clip            = _evenClipRegion;
            CurrPageCanvas.RenderTransform = _transformGroup;
            // Send a message to the ViewModel so it will update the ZIndexes properly
            var ActionMessage = new PageActionMessage()
            {
                action = PageAction.TurningLeft
            };

            Messenger.Default.Send <PageActionMessage>(ActionMessage);
            // Set turning variables accordingly
            _turning   = true;
            _direction = -1;
            _percent   = 0.0;
            TurnTo(_percent);
            _autoTurn = true;
            // Clear menus
            VisualStateManager.GoToState(this, "ClearAll", true);
            _currState  = States.ClearAll;
            _isMenuDown = true;
            // Finish turn
            CompleteTurn();
        }
        private object ChangeZIndexes(PageActionMessage action)
        {
            switch (action.action)
            {
            case PageAction.TurningLeft:
                ZIndexes[4] = 3;
                ZIndexes[2] = 1;
                ZIndexes[1] = 2;
                RaisePropertyChanged("ZIndexes");
                break;

            case PageAction.TurningRight:
                ZIndexes[3] = 3;
                ZIndexes[1] = 1;
                ZIndexes[0] = 2;
                RaisePropertyChanged("ZIndexes");
                break;

            case PageAction.TurningLeftFinished:
                InitializeZOrder(-1);
                break;

            case PageAction.TurningRightFinished:
                InitializeZOrder(1);
                break;

            case PageAction.TurningCanceled:
                InitializeZOrder(0);
                break;

            default:
                return(null);
            }
            return(null);
        }
        /// <summary>
        /// Sets action message for a completed turn
        /// </summary>
        private void InitializeZOrder(PageAction pAction)
        {
            var ActionMessage = new PageActionMessage()
            {
                action = pAction
            };

            Messenger.Default.Send <PageActionMessage>(ActionMessage);
        }
        /// <summary>
        /// Handler for the Pages' mouseLeftButtonDown event. Handles the beginning of a page turn.
        /// </summary>
        private void OnBeginTurn(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (_animating || _currState == States.FirstPageMenuUp)
            {
                return;
            }

            // Hide the pop-up menu when clicking somewhere else on the page
            if (!_isMenuDown)
            {
                if (_pageIndex == 1) // On the first page, show its menu
                {
                    VisualStateManager.GoToState(this, "FirstPageMenuUp", true);
                    _currState = States.FirstPageMenuUp;
                }
                else
                {
                    VisualStateManager.GoToState(this, "MenuDown", true);
                    _currState = States.MenuDown;
                }
                _isMenuDown = true;
                return;
            }

            _mouseClickHorizontalPosition = e.GetPosition(null).Y;
            _mouseClickVerticalPosition   = e.GetPosition(null).X;

            try
            {
                // Turning page to left
                if ((_mouseClickHorizontalPosition >= 440 && Orientation == PageOrientation.LandscapeLeft) ||
                    (_mouseClickHorizontalPosition <= 430 && Orientation == PageOrientation.LandscapeRight))
                {
                    // Check we're not on the last page (i.e. any of the last two pages, as they are duplicated)
                    if (_pageIndex < _totalPages - _duplicatedPages)
                    {
                        _turning   = true;
                        _direction = -1;
                        _percent   = 0.0;
                        _startPos  = e.GetPosition((FrameworkElement)sender).X;
                        ((FrameworkElement)sender).CaptureMouse();
                        _owner = (FrameworkElement)sender;

                        TurnTo(_percent);

                        // Assign clipping regions and transforms to relevant canvases
                        CurrCanvas.Clip                = _oddClipRegion;
                        CurrPageCanvas.Clip            = _evenClipRegion;
                        CurrPageCanvas.RenderTransform = _transformGroup;

                        // Sets action message for a left turn
                        var ActionMessage = new PageActionMessage()
                        {
                            action = PageAction.TurningLeft
                        };
                        Messenger.Default.Send <PageActionMessage>(ActionMessage);
                    }
                    else
                    {
                        _turning = false;
                        return;
                    }
                }
                // Turning page to right
                else if ((_mouseClickHorizontalPosition <= 430 && Orientation == PageOrientation.LandscapeLeft) ||
                         (_mouseClickHorizontalPosition >= 440 && Orientation == PageOrientation.LandscapeRight))
                {
                    // Check we're not on the first page (i.e. the first or the second, as the first one is duplicated)
                    if (_pageIndex > 1)
                    {
                        _turning   = true;
                        _direction = 1;
                        _percent   = 1.0;
                        _startPos  = e.GetPosition((FrameworkElement)sender).X;
                        ((FrameworkElement)sender).CaptureMouse();
                        _owner = (FrameworkElement)sender;

                        // Turn page to specified angle
                        TurnTo(_percent);

                        // Sets action  message for a right turn
                        var ActionMessage = new PageActionMessage()
                        {
                            action = PageAction.TurningRight
                        };
                        Messenger.Default.Send <PageActionMessage>(ActionMessage);

                        // Assign clipping regions and transforms to relevant canvases
                        PrevCanvas.Clip                = _oddClipRegion;
                        PrevPageCanvas.Clip            = _evenClipRegion;
                        PrevPageCanvas.RenderTransform = _transformGroup;
                    }
                    else
                    {
                        _turning = false;
                        return;
                    }
                }
                else
                {
                    _turning = false;
                    return;
                }
            }
            // In very odd situations there are problems with the clipping regions, try again
            catch (ArgumentException)
            {
                resetPagesConfiguration();
                return;
            }
        }
        static void GetResponse(IAsyncResult result)
        {
            try
            {
                HttpWebRequest  request  = (HttpWebRequest)(((object[])result.AsyncState)[0]);
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    RequestType currentType    = (RequestType)(((object[])result.AsyncState)[1]);
                    string      completeString = reader.ReadToEnd();

                    switch (currentType)
                    {
                    case RequestType.InitialToken:
                    {
                        string[] data  = completeString.Split(new char[] { '&' });
                        int      index = data[0].IndexOf("=");
                        StaticData.Token       = data[0].Substring(index + 1, data[0].Length - index - 1);
                        index                  = data[1].IndexOf("=");
                        StaticData.TokenSecret = data[1].Substring(index + 1, data[1].Length - index - 1);

                        WebBrowserTask task = new WebBrowserTask();
                        task.Uri = new Uri("http://api.twitter.com/oauth/authorize?oauth_token=" + StaticData.Token);
                        task.Show();
                        break;
                    }

                    case RequestType.AccessToken:
                    {
                        string[] data  = completeString.Split(new char[] { '&' });
                        int      index = data[0].IndexOf("=");
                        StaticData.Token       = data[0].Substring(index + 1, data[0].Length - index - 1);
                        index                  = data[1].IndexOf("=");
                        StaticData.TokenSecret = data[1].Substring(index + 1, data[1].Length - index - 1);
                        index                  = data[2].IndexOf("=");
                        StaticData.UserID      = data[2].Substring(index + 1, data[2].Length - index - 1);
                        index                  = data[3].IndexOf("=");
                        StaticData.UserName    = data[3].Substring(index + 1, data[3].Length - index - 1);

                        IsoStoreHelper.StoreNewCredentials(StaticData.Token, StaticData.TokenSecret, StaticData.UserID, StaticData.UserName);

                        // Send a message to notify to the MainPage that the authentication request has finished
                        var PageMsg = new PageActionMessage()
                        {
                            action = PageAction.TwitterAuthFinished
                        };
                        Messenger.Default.Send <PageActionMessage>(PageMsg);

                        break;
                    }

                    default:
                    {
                        Debug.WriteLine(completeString);
                        break;
                    }
                    }
                }
            }
            catch (WebException)
            {
                // Delete the credentials to try again later
                IsoStoreHelper.DeleteCredentials();

                // Send a message to notify that there has been something wrong with the request
                var PageMsg = new PageActionMessage()
                {
                    action = PageAction.TwitterAuthFailed
                };
                Messenger.Default.Send <PageActionMessage>(PageMsg);
            }
        }
        /// <summary>
        /// Handles an upcoming message from the View.
        /// </summary>
        /// <param name="action">The PageAction message sent by the View</param>
        private object HandlePageAction(PageActionMessage action)
        {
            switch (action.action)
            {
            case PageAction.TurningLeft:     // Turning page left (i.e. to the next page) animation going on
                ZIndexes[4] = 4;
                ZIndexes[2] = 1;
                ZIndexes[1] = 2;
                MenusZIndex = 3;
                RaisePropertyChanged("ZIndexes");
                break;

            case PageAction.TurningRight:     // Turning page right (i.e. to the previous page) animation going on
                ZIndexes[3] = 4;
                ZIndexes[1] = 1;
                ZIndexes[0] = 3;
                MenusZIndex = 2;
                RaisePropertyChanged("ZIndexes");
                break;

            case PageAction.TurningToCover:     // Same as turning right, but the previous page must be the first one (cover)
                PrevImage     = Images[1];
                PrevPageImage = PageImages[1];
                ZIndexes[3]   = 4;
                ZIndexes[1]   = 1;
                ZIndexes[0]   = 3;
                MenusZIndex   = 2;
                RaisePropertyChanged("ZIndexes");
                break;

            case PageAction.TurningToGallery:     // Same as turning left, but the next page must be the last one (gallery)
                NextImage     = Images[TotalPages - 1];
                NextPageImage = PageImages[TotalPages - 1];
                ZIndexes[4]   = 4;
                ZIndexes[2]   = 1;
                ZIndexes[1]   = 2;
                MenusZIndex   = 3;
                RaisePropertyChanged("ZIndexes");
                break;

            case PageAction.TurningLeftFinished:     // A turn left has finished, expose the next page
                InitializeZOrder(-1);
                break;

            case PageAction.TurningRightFinished:     // A turn right has finished, expose the previous page
                InitializeZOrder(1);
                break;

            case PageAction.TurningToCoverFinished:     // Turn to cover finished, set index accordingly and expose cover
                _currIndex = 2;
                InitializeZOrder(1);
                break;

            case PageAction.TurningToGalleryFinished:     // Turn to gallery finished, set index accordingly and expose gallery
                _currIndex = TotalPages - 1;
                InitializeZOrder(1);
                break;

            case PageAction.TurningCanceled:     // A turning animation has retracted, set z-indexes as they were previously
                InitializeZOrder(0);
                break;



            default:
                return(null);
            }
            return(null);
        }
        private void OnBeginTurn(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (_animating)
            {
                return;
            }

            _mouseClickHorizontalPosition = e.GetPosition(null).Y;

            try
            {
                // Turning page to left
                if ((_mouseClickHorizontalPosition >= 440 && Orientation == PageOrientation.LandscapeLeft) ||
                    (_mouseClickHorizontalPosition <= 430 && Orientation == PageOrientation.LandscapeRight))
                {
                    // Check we're not on the last page
                    if (_pageIndex < _totalPages - 2)
                    {
                        _turning   = true;
                        _direction = -1;
                        _percent   = 0.0;
                        _startPos  = e.GetPosition((FrameworkElement)sender).X;
                        ((FrameworkElement)sender).CaptureMouse();
                        _owner = (FrameworkElement)sender;

                        TurnTo(_percent);

                        // Assign clipping regions and transforms to relevant canvases
                        CurrCanvas.Clip                = _oddClipRegion;
                        CurrPageCanvas.Clip            = _evenClipRegion;
                        CurrPageCanvas.RenderTransform = _transformGroup;

                        // Sets action message for a left turn
                        var ActionMessage = new PageActionMessage()
                        {
                            action = PageAction.TurningLeft
                        };
                        Messenger.Default.Send <PageActionMessage>(ActionMessage);
                    }
                    else
                    {
                        return;
                    }
                }
                // Turning page to right
                else if ((_mouseClickHorizontalPosition <= 430 && Orientation == PageOrientation.LandscapeLeft) ||
                         (_mouseClickHorizontalPosition >= 440 && Orientation == PageOrientation.LandscapeRight))
                {
                    // Check we're not on the first page
                    if (_pageIndex > 1)
                    {
                        _turning   = true;
                        _direction = 1;
                        _percent   = 1.0;
                        _startPos  = e.GetPosition((FrameworkElement)sender).X;
                        ((FrameworkElement)sender).CaptureMouse();
                        _owner = (FrameworkElement)sender;

                        // Turn page to specified angle
                        TurnTo(_percent);

                        // Sets action  message for a right turn
                        var ActionMessage = new PageActionMessage()
                        {
                            action = PageAction.TurningRight
                        };
                        Messenger.Default.Send <PageActionMessage>(ActionMessage);

                        // Assign clipping regions and transforms to relevant canvases
                        PrevCanvas.Clip                = _oddClipRegion;
                        PrevPageCanvas.Clip            = _evenClipRegion;
                        PrevPageCanvas.RenderTransform = _transformGroup;
                    }
                    else
                    {
                        return;
                    }
                }
            }
            // In very odd situations there are problems with the clipping regions, try again
            catch (ArgumentException)
            {
                _turning = false;
                InitializeClipRegions();
                return;
            }
        }