using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;

namespace Fortune1000
{
    /// <summary>
    /// Pivot control that implements a LocalManipulation attached
    /// property.
    /// Setting this property to true in any element contained in the
    /// CoolPivot causes it to suspend the pivot manipulation, letting
    /// the element handle the mouse events itself.
    /// </summary>
    public class CoolPivot : Pivot
    {
        /// <summary>
        /// Identifies the LocalManipulation Dependency Property.
        /// <summary>
        public static readonly DependencyProperty LocalManipulationProperty =
            DependencyProperty.RegisterAttached("LocalManipulation", typeof(bool),
            typeof(CoolPivot), new PropertyMetadata(false));
        /// <summary>
        /// LocalManipulation setter.
        /// </summary>
        public static void SetLocalManipulation(UIElement element, bool value)
        {
            element.SetValue(LocalManipulationProperty, value);
        }
        /// <summary>
        /// LocalManipulation getter.
        /// </summary>
        public static bool GetLocalManipulation(UIElement element)
        {
            return (bool)element.GetValue(LocalManipulationProperty);
        }

        /// <summary>
        /// Prevent manipulation of locked controls.
        /// </summary>
        protected override void OnManipulationStarted(ManipulationStartedRoutedEventArgs e)
        {
            // if the source or any parent has disabled manipulation, stop
            // the manipulation when it starts.
            var fe = e.OriginalSource as FrameworkElement;
            for (; fe != null; fe = VisualTreeHelper.GetParent(fe) as FrameworkElement)
            {
                if ((bool)fe.GetValue(CoolPivot.LocalManipulationProperty))
                {
                    e.Handled = true;
                    e.Complete();
                    break;
                }
            }

            // fire the event as usual
            base.OnManipulationStarted(e);
        }
    }
}
