using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Threading;

using BeWo.Core;
using BeWo.Core.Config;
using BeWo.Core.Service;
using BeWo.ServiceProxy;
using BeWo.View;
using BeWo.View.Detail;
using BeWo.View.Detail.Report;
using BeWo.View.Master;
using BeWo.View.Navigation;
using BeWo.ViewModel;

using BS.Shared;
using BS.Shared.DataContracts;
using BS.Shared.Extensions;

using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Scheduler;
using Hyperlink = System.Windows.Documents.Hyperlink;

namespace BeWo
{
	public enum UIContext
	{
		SupportConcept,
		Customer,
		Person,
		Employee,
		Organisation,
		Team,
		User,
		UserGroup,
		Report,
		Scheduler,
        Wohnheim
	}

	/// <summary>
	///     Interaktionslogik für MainControl.xaml
	/// </summary>
	public partial class MainControl : UserControl
	{
		private const string _PINInfoText = "Um Zugriff auf Ihre Daten zu bekommen, benötigen wir eine PIN.";
		private readonly Stack<Control> _ModalPopUpControls = new Stack<Control>();

		private BeWoView _CurrentDetailView;

		private Control _CurrentModalPopUp;

		private HomeDragPanelView _HomeView;

		private bool _IsMaximized;

		private bool _TermineInitialized;

		private Dictionary<UIContext, BeWoView> _Views = new Dictionary<UIContext, BeWoView>();
		private WaitLayer2 _WaitLayer;

		public MainControl()
		{
			InitializeComponent();

			BeWoApp.MainControl = this;
			InitCommandBindings();
			KeyDown += MainControl_KeyDown;
			NavigateToHomeView();

			EditorLocalizer.Active = new CustomDXEditorLocalizer();
			SchedulerControlLocalizer.Active = new CustomSchedulerLocalizer();

			OpenedModalViewWindows = new List<ModalViewWindow>();

			button_serviceRecord.Content = BeWoApp.AppSettings.TimeRecordingMenuName;
			
			BeWoApp.InitAutoUILocking();

			if (this.button_Scheduler.Visibility == Visibility.Visible && !BeWoApp.AppSettings.IsSchedulerAllowed)
			{
				this.button_Scheduler.Visibility = Visibility.Collapsed;
			}

			if (this.button_Wohnheim.Visibility == Visibility.Visible && !BeWoApp.AppSettings.IsWohnheimAllowed)
			{
				this.button_Wohnheim.Visibility = Visibility.Collapsed;
			}

			if (this.button_ResourceBooking.Visibility == Visibility.Visible && !BeWoApp.AppSettings.ShowResources)
			{
				this.button_ResourceBooking.Visibility = Visibility.Collapsed;
			}
		}

		public List<ModalViewWindow> OpenedModalViewWindows { get; set; }

		internal Dictionary<UIContext, BeWoView> Views
		{
			get { return _Views; }
		}

		public Grid ModalPopUpBackGround { get; private set; }

		public HomeDragPanelView HomeView
		{
			get { return _HomeView; }
			set { _HomeView = value; }
		}

		public BeWoView ActiveView
		{
			get
			{
				if (DetailFrame.Children.Count > 0)
				{
					return DetailFrame.Children[0] as BeWoView;
				}

				return null;
			}
		}

		public bool IsMaximized
		{
			get { return _IsMaximized; }

			set { _IsMaximized = value; }
		}

		private bool _HatNeueTermine;
		public bool HatNeueTermine
		{
			get { return _HatNeueTermine; }
			set
			{
				_HatNeueTermine = value;
				NewAppointmentsOutlinedTextBlock.Visibility = value && BeWoApp.LoggedOnUser != null && BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderAnsehen) ? Visibility.Visible : Visibility.Collapsed;
			}
		}

		public event EventHandler LogoutClicked;

		public void ResetView(UIContext uiContext)
		{
			if (_Views.ContainsKey(uiContext))
			{
				_Views.Remove(uiContext);
			}
		}

		private BeWoView GetViewForUIContext(UIContext uiContext)
		{
			if (!_Views.ContainsKey(uiContext))
			{
				BeWoView view = null;
				switch (uiContext)
				{
					case UIContext.Person:
						view = new PersonNavigationView();
						break;
					case UIContext.Customer:
						view = new CustomerNavigationView();
						break;
					case UIContext.Organisation:
						view = new OrganisationNavigationView();
						break;
					case UIContext.SupportConcept:
						view = new SupportConceptNavigationView();
						break;
					case UIContext.Team:
						view = new TeamNavigationView();
						break;
					case UIContext.User:
						view = new UserNavigationView();
						break;
					case UIContext.UserGroup:
						view = new UserGroupNavigationView();
						break;
					case UIContext.Employee:
						view = new EmployeeNavigationView();
						break;
					case UIContext.Report:
						view = new ReportView();
						break;
					case UIContext.Scheduler:
						view = new SchedulerMasterView();
						break;
                    case UIContext.Wohnheim:
                        view = new WohnheimNavigationView();
                        break;
				}
				_Views[uiContext] = view;
			}
			return _Views[uiContext];
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public void AnimateOpacity(double pOpacitiy, double pDuration)
		{
			// System.Windows.Media.TransformGroup group = this.DetailFrame.RenderTransform as System.Windows.Media.TransformGroup;
			// System.Windows.Media.ScaleTransform scale = group.Children[0] as System.Windows.Media.ScaleTransform;
			var lAnimation = new DoubleAnimation();

			// lAnimation.From = scale.ScaleX;
			// lAnimation.To = pOpacitiy;
			lAnimation.From = DetailFrame.Opacity;
			lAnimation.To = pOpacitiy;
			lAnimation.Duration = TimeSpan.FromMilliseconds(pDuration);
			DetailFrame.BeginAnimation(OpacityProperty, lAnimation);

			// scale.BeginAnimation(System.Windows.Media.ScaleTransform.ScaleXProperty, lAnimation);
			// scale.BeginAnimation(System.Windows.Media.ScaleTransform.ScaleYProperty, lAnimation);
		}

		public void AnimateOpacity(double pOpacitiy)
		{
			AnimateOpacity(pOpacitiy, 500);
		}

		public void ChangePopUpOpacityMode(bool isPopUpVisible)
		{
			if (isPopUpVisible)
			{
				AnimateOpacity(0.5, 200);
			}
			else
			{
				AnimateOpacity(1, 100);
			}
		}

		public void CloseCurrentPopUp()
		{
			if (ModalPopUpBackGround != null)
			{
				Dispatcher.BeginInvoke(
					DispatcherPriority.Normal,
					(Action) delegate
					{
						grid_main.Children.Remove(_CurrentModalPopUp);
						_CurrentModalPopUp = null;
						if (_ModalPopUpControls.Count == 0)
						{
							grid_main.Children.Remove(ModalPopUpBackGround);
							ModalPopUpBackGround = null;
						}
						else
						{
							Control control = _ModalPopUpControls.Pop();
							_CurrentModalPopUp = control;
							grid_main.Children.Add(control);
							Panel.SetZIndex(control, int.MaxValue);
						}
					});
			}
		}

		public void EndWaiting()
		{
			Dispatcher.BeginInvoke(
				DispatcherPriority.Normal,
				(Action) delegate
				{
					if (_WaitLayer != null)
					{
						grid_main.Children.Remove(_WaitLayer);
						_WaitLayer = null;
					}
				});
		}

		public void NavigateToServiceRecordView(long? supportConceptOid)
		{
			if (DoSaveCheck())
			{
				VMFactory.CreateServiceRecordVMAsync(
					BeWoApp.LoggedOnUser.Employee.EmployeeOid,
					vm => this.Dispatch(
						delegate
						{
							vm.DispatcherObject = this;
							NavigateTo(new ServiceRecordView2(vm, supportConceptOid));
						}));
			}
		}

		public void NavigateToAdditionalServiceView(long? supportConceptOid)
		{
			if (DoSaveCheck())
			{
				VMFactory.CreateServiceRecordVMAsync(
					BeWoApp.LoggedOnUser.Employee.EmployeeOid,
					vm => Cache.GetInstance().GetAllActiveAndArchivedCustomerCompact(
						c => this.Dispatch(
							delegate
							{
								vm.DispatcherObject = this;

								if (vm.NewVM != null)
									vm.NewVM.ServiceRecordType = ServiceRecordTypeId.AdditionalService;

								NavigateTo(new AdditionalServiceView(vm, c));
							})));
				}
		}

		public void ShowControlAsModalPopUp(Control control)
		{
			ShowControlAsModalPopUp(control, HorizontalAlignment.Center, VerticalAlignment.Center);
		}

		public void ShowControlAsModalPopUp(Control control, HorizontalAlignment ha, VerticalAlignment va)
		{
			Dispatcher.BeginInvoke(
				DispatcherPriority.Normal,
				(Action) delegate
				{
					if (_CurrentModalPopUp != null)
					{
						grid_main.Children.Remove(_CurrentModalPopUp);
						_ModalPopUpControls.Push(_CurrentModalPopUp);
					}
					else
					{
						ShowModalBackground();
					}

					_CurrentModalPopUp = control;
					control.HorizontalAlignment = ha;
					control.VerticalAlignment = va;
					Grid.SetColumnSpan(control, 3);
					Grid.SetRowSpan(control, 3);
					grid_main.Children.Add(control);
					Panel.SetZIndex(control, int.MaxValue);
				});
		}

		public void StartWaiting()
		{
			Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) StartWaitingImmediately);
		}

		public void StartWaitingImmediately()
		{
			if (_WaitLayer == null)
			{
				_WaitLayer = new WaitLayer2();
				Grid.SetColumnSpan(_WaitLayer, 3);
				Grid.SetRowSpan(_WaitLayer, 3);
				grid_main.Children.Add(_WaitLayer);
				Panel.SetZIndex(_WaitLayer, int.MaxValue);
				_WaitLayer.RefreshUI();
			}
		}

		internal void ClearDetailFrame()
		{
			foreach (var window in BeWoApp.CurrentBeWo.MainWindow.OwnedWindows)
			{
				((System.Windows.Window)window).Close();
			}

			BeWoView lOld = null;
			if (DetailFrame.Children.Count == 1)
			{
				lOld = DetailFrame.Children[0] as BeWoView;
			}

			_CurrentDetailView = null;

			if (lOld != null)
			{
				if (lOld is HomeDragPanelView)
				{
					var hdpv = lOld as HomeDragPanelView;
					hdpv.SaveState();
					BeWoApp.SaveAppSettings();
				}

				lOld.BlendOutComplete += (s, e) => DetailFrame.Children.Remove(lOld);
				lOld.BlendOut();
			}

			DetailFrame.Children.Clear();
		}

		internal void Maximize()
		{
			var animation = new ThicknessAnimationUsingKeyFrames();
			var t = new Thickness(-5, 0, -5, 0);
			animation.KeyFrames.Add(new SplineThicknessKeyFrame(t, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)), new KeySpline(1, 0, 1, 1)));

			animation.Completed += maximizeAnimation_Completed;

			AnimateToolbarOut(0);
			DetailFrame.BeginAnimation(MarginProperty, animation);

			BeWoApp.AppSettings.WindowState = AppSettings.WindowStateType.Maximised;
			BeWoApp.SaveAppSettings();

			// toolbarButtonPanel.Visibility = Visibility.Hidden;
			// toolbarBord.Visibility = Visibility.Hidden;
			// LogoutButtonPanel.Visibility = Visibility.Hidden;
			////###HOMEVIEW HomeButtonPanel.Visibility = Visibility.Hidden;
			// toolbarScrollViewer.Visibility = Visibility.Hidden;
		}

		internal void Minimize()
		{
			var animation = new ThicknessAnimationUsingKeyFrames();
			var t = new Thickness(140, 35, 140, 85);
			animation.KeyFrames.Add(new SplineThicknessKeyFrame(t, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)), new KeySpline(0, 1, 1, 1)));

			animation.Completed += minimizeAnimation_Completed;

			AnimateToolbarIn(0);
			DetailFrame.BeginAnimation(MarginProperty, animation);

			BeWoApp.AppSettings.WindowState = AppSettings.WindowStateType.Default;
			BeWoApp.SaveAppSettings();

			// toolbarButtonPanel.Visibility = Visibility.Visible;
			// toolbarBord.Visibility = Visibility.Visible;
			// LogoutButtonPanel.Visibility = Visibility.Visible;
			////###HOMEVIEW HomeButtonPanel.Visibility = Visibility.Visible;
			// toolbarScrollViewer.Visibility = Visibility.Visible;
		}

		internal void NavigateTo(BeWoView pElement)
		{
			if (BeWoApp.RenderTier < 2)
				NavigateToWithoutFade(pElement);
			else
				NavigateToWithFade(pElement);
		}

		internal void NavigateToWithoutFade(BeWoView pElement)
		{
			if (pElement == null)
			{
				NavigateToHomeView();
			}
			else
			{
				if (DetailFrame.Children.Count == 1)
				{
					var lOld = DetailFrame.Children[0] as BeWoView;

					if (lOld != null)
					{
						if (lOld is HomeDragPanelView)
						{
							var hdpv = lOld as HomeDragPanelView;
							hdpv.SaveState();
							BeWoApp.SaveAppSettings();
						}
					}
					DetailFrame.Children.Clear();
				}

				if (pElement != null)
				{
					DetailFrame.Children.Add(pElement);
				}

				_CurrentDetailView = pElement;

				DetailFrame.Children.RemoveRange(2);
			}
		}

		internal void NavigateToWithFade(BeWoView pElement)
		{
			if (pElement == null)
			{
				NavigateToHomeView();
			}
			else
			{
				BeWoView lOld = null;
				if (DetailFrame.Children.Count > 0)
				{
					lOld = DetailFrame.Children[0] as BeWoView;

					if (DetailFrame.Children.Count > 1)
					{
						DetailFrame.Children.RemoveRange(1);
					}
					if (lOld != null && lOld.Equals(pElement))
						return;
				}


				if (pElement != null)
				{
					pElement.Opacity = 0;
					DetailFrame.Children.Add(pElement);
					pElement.Focus();
					pElement.BlendIn();

					// Object obj = pElement.Template.FindName("togglebutton_maximise", pElement);
					// obj = pElement.FindName("togglebutton_maximise");
					// if (maximizeButton != null)
					// {
					// maximizeButton.IsChecked = IsMaximized;
					// }
				}

				_CurrentDetailView = pElement;

				if (lOld != null)
				{
					if (lOld is HomeDragPanelView)
					{
						var hdpv = lOld as HomeDragPanelView;
						hdpv.SaveState();
						BeWoApp.SaveAppSettings();
					}

					lOld.BlendOutComplete += (s, e) =>
					{
						if (DetailFrame.Children.Count > 1)
							DetailFrame.Children.Remove(lOld);
					};
					lOld.BlendOut();
				}

				DetailFrame.Children.RemoveRange(2);
			}
		}

		protected virtual void FirePropertyChanged(string pPropertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(pPropertyName));
			}
		}

		private void AnimateToolbarIn(int delay)
		{
			var animation = new DoubleAnimationUsingKeyFrames();

			animation.BeginTime = new TimeSpan(0, 0, 0, 0, delay);

			animation.KeyFrames.Add(new SplineDoubleKeyFrame(-5, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)), new KeySpline(0, 1, 1, 1)));
			animation.KeyFrames.Add(new SplineDoubleKeyFrame(0, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 1000)), new KeySpline(0.35, 0.5, 0.5, 0.9)));

			var group = (TransformGroup) toolbarRoot.RenderTransform;
			var trans = (TranslateTransform) group.Children[3];

			var animationButtons = new DoubleAnimationUsingKeyFrames();
			animationButtons.BeginTime = new TimeSpan(0, 0, 0, 0, delay);
			animationButtons.KeyFrames.Add(new SplineDoubleKeyFrame(0, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)), new KeySpline(0, 1, 1, 1)));

			var groupButtons = (TransformGroup) toolbarContent.RenderTransform;
			var transButtons = (TranslateTransform) groupButtons.Children[3];

			transButtons.BeginAnimation(TranslateTransform.YProperty, animationButtons);

			trans.BeginAnimation(TranslateTransform.YProperty, animation);
		}

		private void AnimateToolbarOut(int delay)
		{
			var animation = new DoubleAnimationUsingKeyFrames();

			animation.BeginTime = new TimeSpan(0, 0, 0, 0, delay);

			animation.KeyFrames.Add(new SplineDoubleKeyFrame(45, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)), new KeySpline(1, 0, 1, 1)));

			var group = (TransformGroup) toolbarRoot.RenderTransform;
			var trans = (TranslateTransform) group.Children[3];

			var animationButtons = new DoubleAnimationUsingKeyFrames();
			animationButtons.BeginTime = new TimeSpan(0, 0, 0, 0, delay);
			animationButtons.KeyFrames.Add(new SplineDoubleKeyFrame(100, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)), new KeySpline(1, 0, 1, 1)));

			var groupButtons = (TransformGroup) toolbarContent.RenderTransform;
			var transButtons = (TranslateTransform) groupButtons.Children[3];

			transButtons.BeginAnimation(TranslateTransform.YProperty, animationButtons);
			trans.BeginAnimation(TranslateTransform.YProperty, animation);
		}

		public bool DoSaveCheck()
		{
			return _CurrentDetailView == null || _CurrentDetailView.DoSaveCheck();
		}

		private void InitCommandBindings()
		{
			CommandBindings.Add(
				new CommandBinding(
					ApplicationCommands.Save,
					(s, e) =>
					{
						if (_CurrentModalPopUp == null)
						{
							_CurrentDetailView.SaveData();
						}
						else
						{
							_CurrentDetailView.ModalPopUpSaveInvoked();
						}
					},
					(s, e) =>
					{
						if (_CurrentModalPopUp == null)
						{
							e.CanExecute = _CurrentDetailView != null ? _CurrentDetailView.IsDirty : false;
						}
						else
						{
							e.CanExecute = _CurrentDetailView != null && (_CurrentModalPopUp is BeWoView && ((BeWoView) _CurrentModalPopUp).IsDirty);
						}
					}));

			CommandBindings.Add(new CommandBinding(BeWoCommands.Excel, (s, e) => _CurrentDetailView.ExportToExcel(e.Parameter as string), (s, e) => e.CanExecute = _CurrentDetailView != null ? _CurrentDetailView.CanExcelExport : false));

			CommandBindings.Add(new CommandBinding(ApplicationCommands.Delete, (s, e) => _CurrentDetailView.Delete(), (s, e) => e.CanExecute = _CurrentDetailView != null ? _CurrentDetailView.CanDelete : false));

			CommandBindings.Add(new CommandBinding(BeWoCommands.Word, (s, e) => _CurrentDetailView.ExportToWord(e.Parameter as string), (s, e) => e.CanExecute = _CurrentDetailView != null ? _CurrentDetailView.CanWordExport : false));

			CommandBindings.Add(
				new CommandBinding(
					ApplicationCommands.Close,
					(s, e) =>
					{
						if (_CurrentModalPopUp == null && DoSaveCheck())
						{
							if (_CurrentDetailView.ParentView != null)
								_CurrentDetailView.ParentView.ChildViewClosed();

							NavigateToParentView(_CurrentDetailView.ParentView);
						}
						else
						{
							_CurrentDetailView.ModalPopUpCloseInvoked();
						}
					}, (s, e) => e.CanExecute = _CurrentDetailView != null));
		}

		private void NavigateToParentView(BeWoView beWoView)
		{
			if (beWoView is CustomerNavigationView && !_Views.ContainsKey(UIContext.Customer))
			{
				_Views.Add(UIContext.Customer, beWoView);
			}
			else if (beWoView is EmployeeNavigationView && !_Views.ContainsKey(UIContext.Employee))
			{
				_Views.Add(UIContext.Employee, beWoView);
			}
			else if (beWoView is OrganisationNavigationView && !_Views.ContainsKey(UIContext.Organisation))
			{
				_Views.Add(UIContext.Organisation, beWoView);
			}
			else if (beWoView is PersonNavigationView && !_Views.ContainsKey(UIContext.Person))
			{
				_Views.Add(UIContext.Person, beWoView);
			}
			else if (beWoView is SupportConceptNavigationView && !_Views.ContainsKey(UIContext.SupportConcept))
			{
				_Views.Add(UIContext.SupportConcept, beWoView);
			}
			else if (beWoView is TeamNavigationView && !_Views.ContainsKey(UIContext.Team))
			{
				_Views.Add(UIContext.Team, beWoView);
			}
			else if (beWoView is UserNavigationView && !_Views.ContainsKey(UIContext.User))
			{
				_Views.Add(UIContext.User, beWoView);
			}
			else if (beWoView is UserGroupNavigationView && !_Views.ContainsKey(UIContext.UserGroup))
			{
				_Views.Add(UIContext.UserGroup, beWoView);
            }
            else if (beWoView is WohnheimNavigationView && !_Views.ContainsKey(UIContext.Wohnheim))
            {
                _Views.Add(UIContext.Wohnheim, beWoView);
            }
			NavigateTo(beWoView);
		}

		private void MainControl_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Back)
			{
				e.Handled = true;
			}
		}

		private void NavigateToHomeView()
		{
			if (_HomeView == null)
			{
				_HomeView = new HomeDragPanelView();
			}
			else
			{
				_HomeView.ReorderPanels();
			}

			NavigateTo(_HomeView);


			// VarFieldListVM v = new VarFieldListVM(l);

			// NavigateTo(new VarFieldView(v));
		}

		private void OnLoadedStoryboard_Completed(object sender, EventArgs e)
		{
			if (BeWoApp.AppSettings.WindowState == AppSettings.WindowStateType.Maximised)
			{
				Maximize();
				IsMaximized = true;
				FirePropertyChanged("IsMaximized");
			}
		}

		internal void ShowModalBackground()
		{
			ModalPopUpBackGround = new Grid();
			ModalPopUpBackGround.IsHitTestVisible = true;
			ModalPopUpBackGround.Background = Brushes.White;
			ModalPopUpBackGround.Opacity = .5;
			Grid.SetColumnSpan(ModalPopUpBackGround, 3);
			Grid.SetRowSpan(ModalPopUpBackGround, 3);
			grid_main.Children.Add(ModalPopUpBackGround);
			Panel.SetZIndex(ModalPopUpBackGround, int.MaxValue - 1);
		}

		private void logoutanimation_Completed(object sender, EventArgs e)
		{
			//var navigationService = NavigationService.GetNavigationService(this);
			//if (navigationService != null)
			//{
			// navigationService.Navigate(new LoginPage());
			BeWoApp.UserName = string.Empty;
			BeWoApp.UserPassword = string.Empty;

			// BeWoApp.Tenant = "";
			BeWoApp.LoggedOnUser = null;
			//}
			if (LogoutClicked != null)
				LogoutClicked(null, new EventArgs());
		}

		private void btn_home_Click(object sender, RoutedEventArgs e)
		{
			if (!(_CurrentDetailView is HomeDragPanelView) && DoSaveCheck())
			{
				NavigateToHomeView();
			}
		}

		private void button_AccountingTransacation_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(new FinanceView());
			}
		}

		private void button_Administration_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(new AdministrationView());
			}
		}

		// private void ExcelExport_RequestNavigate(object sender, RequestNavigateEventArgs e)
		// {
		// BeWoCommands.Excel.Execute(LinkEngine.ExcelFileId, ExcelExport);
		// LinkEngine.GenerateNewExcelLink();
		// }

		// private void WordExport_RequestNavigate(object sender, RequestNavigateEventArgs e)
		// {
		// BeWoCommands.Word.Execute(LinkEngine.WordFileId, WordExport);
		// LinkEngine.GenerateNewWordLink();
		// }

		private void button_Customer_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.Customer));
			}
		}
//-----------------------------------------------------------------------------------------------------------------
        //############# Button Wohnheim klick #######################################################
        private void button_Wohnheim_Click(object sender, RoutedEventArgs e)
        {
            if (DoSaveCheck())
            {
                NavigateTo(GetViewForUIContext(UIContext.Wohnheim));
            }
        }
        //############# Button Wohnheim klick #######################################################
//------------------------------------------------------------------------------------------------------------------
		private void button_Employee_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.Employee));
			}
		}

		private void button_Home(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				// NavigateTo(new HomeView());
				NavigateTo(new HomeDragPanelView());
			}
		}

		private void button_Logout(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				Cache.GetInstance().ClearAll();
				_Views = new Dictionary<UIContext, BeWoView>();

                _HomeView.CloseConnection();

				var animation = new DoubleAnimationUsingKeyFrames();

				animation.KeyFrames.Add(new SplineDoubleKeyFrame(100, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)), new KeySpline(1, 0, 1, 1)));

				var group = (TransformGroup) toolbarRoot.RenderTransform;
				var trans = (TranslateTransform) group.Children[3];

				trans.BeginAnimation(TranslateTransform.YProperty, animation);

				animation = new DoubleAnimationUsingKeyFrames();
				animation.Completed += logoutanimation_Completed;

				animation.KeyFrames.Add(new SplineDoubleKeyFrame(-200, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)), new KeySpline(1, 0, 1, 1)));

				group = (TransformGroup) image.RenderTransform;
				trans = (TranslateTransform) group.Children[3];

				trans.BeginAnimation(TranslateTransform.XProperty, animation);
				ClearDetailFrame();
			}
		}

		private void button_Organisation_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.Organisation));
			}
		}

		private void button_Person_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.Person));
			}
		}

		private void button_Reports_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.Report));
			}
		}

		private void button_ResourceBooking_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				ServiceFacade.DoResourceServiceAsync(
					s1 => s1.GetAllResources(),
					r1 => ServiceFacade.DoEmployeeServiceAsync(
						s2 => s2.GetAllActiveEmployeesCompact(),
						r2 =>
						{
							if (r1.Count > 0 && r2.Count > 0)
							{
								try
								{
									Dictionary<ValueListEntryDC, List<ResourceDC>> lCategoriesToResources = r1.Select(res => res.ResourceCategory).Distinct().OrderBy(cat => cat.TypeDescription).Select(cat => new {Key = cat, Value = r1.Where(res => res.ResourceCategory.Equals(cat)).OrderBy(res => res.Name).ToList()}).ToDictionary(a => a.Key, a => a.Value);

									this.Dispatch(delegate { NavigateTo(new BookingView(lCategoriesToResources, r2, BeWoApp.LoggedOnUser.Employee)); });
								}
								catch (Exception)
								{
									MessageBox.Show("Bitte legen Sie zunächst unter Verwaltung Resourcen und Resourcenkategorien an.");
								}
							}
						}));
			}
		}

		private void button_Scheduler_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.Scheduler));
			}
		}

		private void button_SupportConcept_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.SupportConcept));
			}
		}

		private void button_Team_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.Team));
			}
		}

		private void button_UserGroup_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.UserGroup));
			}
		}

		private void button_User_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(GetViewForUIContext(UIContext.User));
			}
		}

		//private void button_assessmentSheetEntry_Click(object sender, RoutedEventArgs e)
		//{
		//    if (this.DoSaveCheck())
		//    {
		//        this.NavigateTo(new AssessmentSheetEntryView());
		//    }
		//}

		private void button_publicQuerys_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				ServiceFacade.DoQueryServiceAsync(s => s.GetAllQueriesOfType(QueryType.Public), cb => this.Dispatch(delegate { NavigateTo(new QueryView(cb)); }));
			}
		}

		private void button_resources_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				VMFactory.CreateResourceListVMAsync(cb => this.Dispatch(delegate { NavigateTo(new RessourceView(cb)); }));
			}
		}

		private void button_serviceRecord_Click(object sender, RoutedEventArgs e)
		{
			NavigateToServiceRecordView(null);
		}

		private void button_additionalService_Click(object sender, RoutedEventArgs e)
		{
			NavigateToAdditionalServiceView(null);
		}

		private void maximizeAnimation_Completed(object sender, EventArgs e)
		{
			_IsMaximized = true;
		}

		private void minimizeAnimation_Completed(object sender, EventArgs e)
		{
			_IsMaximized = false;
		}

		private void toolbarRoot_MouseEnter(object sender, MouseEventArgs e)
		{
			if (_IsMaximized)
			{
				AnimateToolbarIn(500);
			}
		}

		private void toolbarRoot_MouseLeave(object sender, MouseEventArgs e)
		{
			if (_IsMaximized)
			{
				AnimateToolbarOut(200);
			}
		}

		private void toolbarScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
		{
			e.Handled = true;
		}

		private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
		{
			// Hier Token anfordern; Hier nicht notwendig -> Link auf www.beyondsoft.de
			Process.Start(new ProcessStartInfo((sender as Hyperlink).NavigateUri.ToString()));
		}

		private void button_Support_Click(object sender, RoutedEventArgs e)
		{
			var mailButton = new Button
			{
				Content = "*",
				FontFamily = new FontFamily("Wingdings"),
				FontSize = 16,
				Width = 25,
				Margin = new Thickness(5),
				HorizontalContentAlignment = HorizontalAlignment.Center,
				VerticalContentAlignment = VerticalAlignment.Center
			};


			var phoneButton = new Button
			{
				Content = ")",
				FontFamily = new FontFamily("Wingdings"),
				FontSize = 16,
				Width = 25,
				Margin = new Thickness(5),
				HorizontalContentAlignment = HorizontalAlignment.Center,
				VerticalContentAlignment = VerticalAlignment.Center
			};


			var cancelButton = new Button {Content = "Schließen"};
			cancelButton.Margin = new Thickness(5);

			var mailLabel = new Label
			{
				Content = "Support-Mail schreiben",
				FontWeight = FontWeights.Bold,
				Margin = new Thickness(5),
				HorizontalContentAlignment = HorizontalAlignment.Center,
				VerticalContentAlignment = VerticalAlignment.Center
			};

			//var mailButtonLabel = new Button
			//{
			//	Content = "Support-Mail schreiben",
			//	FontWeight = FontWeights.Bold,
			//	Margin = new Thickness(5),
			//	HorizontalContentAlignment = HorizontalAlignment.Center,
			//	VerticalContentAlignment = VerticalAlignment.Center,
			//	Style = null,
			//	Background = Brushes.Transparent
			//};
			//mailButtonLabel.Content = mailLabel;

			var textBlockMail = new TextBlock
			{
				Foreground = Brushes.Black,
				Margin = new Thickness(45, 5, 5, 5),
				Text = "Wenn Sie auf das Brief-Symbol klicken öffnet sich ein Fenster,\nin dem Sie eine E-Mail an den BeWoPlaner-Support formulieren können"
			};
			var phoneLabel = new Label
			{
				Content = "PIN für Support-Anruf erhalten",
				FontWeight = FontWeights.Bold,
				Margin = new Thickness(5),
				HorizontalContentAlignment = HorizontalAlignment.Center,
				VerticalContentAlignment = VerticalAlignment.Center
			};

			var textBlockPhone = new TextBlock
			{
				Foreground = Brushes.Black,
				Margin = new Thickness(45, 5, 5, 5),
				Text = "Wenn Sie auf das PIN-Symbol klicken, wird Ihnen eine zufällige Support-PIN angezeigt.\n\n" +
				       "Benötigen wir zur Lösung einer Support-Anfrage den Zugriff auf Ihre Datenbank,\n" +
				       "werden Sie vom Support-Mitarbeiter gebeten, ihm eine solche Support-PIN zu übermitteln.\n" +
				       "Diese PIN ist nur einmalig nutzbar/gültig. Sie wird nicht automatisch an den Support übermittelt.\n" +
				       "Dies stellt sicher, dass ein Support-Mitarbeiter nicht ohne Ihre Einwilligung auf Ihre Datenbank zugreifen kann.\n" +
				       "Jeder Support-Zugriff auf Ihre Datenbank wird zudem mit Hilfe der PIN protokolliert."
			};

			BeWoWindow bewoWindow = BeWoWpfUtils.CreateBeWoPopupWindow(300, 1000, true);

			cancelButton.Click += delegate { bewoWindow.Close(); };

			
			mailButton.Click += delegate
			{
				bewoWindow.Close();
				CreateSupportMailWindow();
			};

			phoneButton.Click += delegate
			{
				bewoWindow.Close();
				CreateSupportRequestWindow();
			};


			//var mailHelpButton = new Button
			//{
			//	Content = "?",
			//	Width = 25,
			//	Margin = new Thickness(5),
			//	HorizontalContentAlignment = HorizontalAlignment.Center,
			//	VerticalContentAlignment = VerticalAlignment.Center,
			//	ToolTip = "Wenn Sie auf das Brief-Symbol klicken öffnet sich ein Fenster,\nin dem Sie eine E-Mail an den BeWoPlaner-Support formulieren können"
			//};

			//var phoneHelpButton = new Button
			//{
			//	Content = "?",
			//	Width = 25,
			//	Margin = new Thickness(5),
			//	HorizontalContentAlignment = HorizontalAlignment.Center,
			//	VerticalContentAlignment = VerticalAlignment.Center,
			//	ToolTip = "Wenn Sie auf das PIN-Symbol klicken, wird Ihnen eine zufällige Support-PIN angezeigt.\n\n" +
			//			  "Benötigen wir zur Lösung einer Support-Anfrage den Zugriff auf Ihre Datenbank,\n" +
			//			  "werden Sie vom Support-Mitarbeiter gebeten, ihm eine solche Support-PIN zu übermitteln.\n" +
			//			  "Diese PIN ist nur einmalig nutzbar/gültig. Sie wird nicht automatisch an den Support übermittelt.\n" +
			//			  "Dies stellt sicher, dass ein Support-Mitarbeiter nicht ohne Ihre Einwilligung auf Ihre Datenbank zugreifen kann.\n"+
			//			  "Jeder Support-Zugriff auf Ihre Datenbank wird zudem mit Hilfe der PIN protokolliert."


			//};

			var centeredStackPanel = new StackPanel {Orientation = Orientation.Vertical, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center};
			var mailStackPanel = new StackPanel {Orientation = Orientation.Horizontal};
			var phoneStackPanel = new StackPanel {Orientation = Orientation.Horizontal};


			mailStackPanel.Children.Add(mailButton);
			mailStackPanel.Children.Add(mailLabel);


			phoneStackPanel.Children.Add(phoneButton);
			phoneStackPanel.Children.Add(phoneLabel);


			centeredStackPanel.Children.Add(mailStackPanel);
			centeredStackPanel.Children.Add(textBlockMail);
			centeredStackPanel.Children.Add(phoneStackPanel);
			centeredStackPanel.Children.Add(textBlockPhone);
			centeredStackPanel.Children.Add(cancelButton);


			var grid = new Grid
			{
				Background = (LinearGradientBrush) FindResource("ObjectEditBackgroundBrush")
			};

			grid.Children.Add(centeredStackPanel);

			bewoWindow.GroupBoxContent = grid;
			bewoWindow.rootGroupBox.Header = "Support";
			bewoWindow.Owner = BeWoApp.CurrentBeWo.MainWindow;
			bewoWindow.Show();
		}

	    private void CreateSupportMailWindow()
		{
			BeWoWindow bewoWindow = BeWoWpfUtils.CreateBeWoPopupWindow(600, 800);
			bewoWindow.SizeChanged += delegate
			{
				bewoWindow.Left = ActualWidth/2 - bewoWindow.Width/2;
				bewoWindow.Top = ActualHeight/2 - bewoWindow.Height/2;
			};

			//var grid = new Grid
			//{
			//	Background = (LinearGradientBrush) FindResource("ObjectEditBackgroundBrush")
			//};

			//var infoGrid = new Grid
			//{
			//	Background = (LinearGradientBrush) FindResource("ObjectEditBackgroundBrush")
			//};

			//var beschreibungLabel = new Label {Content = "Hier können Sie eine E-Mail an den BeWoPlaner-Support formulieren.", Margin = new Thickness(3)};
			//var betreffLabel = new Label {Content = "Betreff:", Margin = new Thickness(3)};
			//var betreffTextBox = new TextBox {Margin = new Thickness(3, 3, 3, 0)};
			//var nachrichtsTextBox = new TextBox
			//{
			//	Margin = new Thickness(3),
			//	AcceptsReturn = true,
			//	VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
			//	HorizontalScrollBarVisibility = ScrollBarVisibility.Auto
			//};
			//var pinCheckBox = new CheckBox
			//{
			//	Margin = new Thickness(3),
			//	Content = "PIN anfügen",
			//	ToolTip = "Nur mit dieser PIN erhält ein Servicemitarbeiter Zugang zu Ihren Daten"
			//};
			//var abbrechenButton = new Button {Margin = new Thickness(3), Content = "Abbrechen"};
			//var schliessenButton = new Button {Margin = new Thickness(3), Content = "Schließen"};
			//var sendenButton = new Button
			//{
			//	Margin = new Thickness(3),
			//	Content = "Senden",
			//	HorizontalAlignment = HorizontalAlignment.Left
			//};
			//var zurueckButton = new Button
			//{
			//	Margin = new Thickness(3),
			//	Content = "Zurück"
			//};
			//var weiterButton = new Button
			//{
			//	Margin = new Thickness(3),
			//	Content = "Weiter",
			//	HorizontalAlignment = HorizontalAlignment.Left
			//};
			//weiterButton.Click += delegate { bewoWindow.GroupBoxContent = infoGrid; };

			//zurueckButton.Click += delegate
			//{
			//	bewoWindow.GroupBoxContent = grid;
			//	bewoWindow.Left = ActualWidth/2 - bewoWindow.Width/2;
			//	bewoWindow.Top = ActualHeight/2 - bewoWindow.Height/2;
			//};

			//grid.ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto});
			//grid.ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto});
			//grid.ColumnDefinitions.Add(new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)});
			//grid.ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto});

			//grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});
			//grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});
			//grid.RowDefinitions.Add(new RowDefinition {Height = new GridLength(1, GridUnitType.Star)});
			//grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});
			//grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});

			//Grid.SetRow(beschreibungLabel, 0);
			//Grid.SetRow(betreffLabel, 1);
			//Grid.SetRow(betreffTextBox, 1);
			//Grid.SetRow(nachrichtsTextBox, 2);
			//Grid.SetRow(abbrechenButton, 3);
			//Grid.SetRow(weiterButton, 3);

			//Grid.SetColumn(betreffLabel, 0);
			//Grid.SetColumn(betreffTextBox, 1);
			//Grid.SetColumn(nachrichtsTextBox, 0);
			//Grid.SetColumn(abbrechenButton, 3);
			//Grid.SetColumn(weiterButton, 0);

			//Grid.SetColumnSpan(beschreibungLabel, 4);
			//Grid.SetColumnSpan(betreffTextBox, 3);
			//Grid.SetColumnSpan(nachrichtsTextBox, 4);
			//Grid.SetColumnSpan(weiterButton, 2);

			//grid.Children.Add(beschreibungLabel);
			//grid.Children.Add(betreffLabel);
			//grid.Children.Add(betreffTextBox);
			//grid.Children.Add(nachrichtsTextBox);
			//grid.Children.Add(abbrechenButton);
			//grid.Children.Add(weiterButton);

			//abbrechenButton.Click += delegate { bewoWindow.Close(); };
			//schliessenButton.Click += delegate { bewoWindow.Close(); };

			//sendenButton.Click += delegate
			//{
			//	if (betreffTextBox.Text.IsNullOrEmpty())
			//	{
			//		MessageBox.Show("Bitte geben Sie einen Betreff an.", "Senden nicht möglich",
			//			MessageBoxButton.OK, MessageBoxImage.Warning);
			//		return;
			//	}

			//	if (nachrichtsTextBox.Text.IsNullOrEmpty())
			//	{
			//		MessageBox.Show("Bitte tragen Sie eine Nachricht ein.", "Senden nicht möglich",
			//			MessageBoxButton.OK, MessageBoxImage.Warning);
			//		return;
			//	}


			//	string nachricht = nachrichtsTextBox.Text;
			//	if (pinCheckBox.IsChecked.HasValue && pinCheckBox.IsChecked.Value)
			//	{
			//		nachricht += string.Format("\r\rPIN: {0}", GeneratePIN());
			//	}
			//	EMailVersenden(betreffTextBox.Text, nachricht);
			//};

			//var infoTextBlock = new TextBlock
			//{
			//	Text = _PINInfoText,
			//	Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0)),
			//	Margin = new Thickness(3),
			//	TextWrapping = TextWrapping.Wrap,
			//	TextAlignment = TextAlignment.Center,
			//	VerticalAlignment = VerticalAlignment.Center
			//};

			//var naviStackPanel = new StackPanel {Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right};
			//naviStackPanel.Children.Add(zurueckButton);
			//naviStackPanel.Children.Add(schliessenButton);

			//infoGrid.RowDefinitions.Add(new RowDefinition {Height = new GridLength(1, GridUnitType.Star)});
			//infoGrid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});
			//infoGrid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});

			//infoGrid.ColumnDefinitions.Add(new ColumnDefinition());
			//infoGrid.ColumnDefinitions.Add(new ColumnDefinition());

			//Grid.SetRow(infoTextBlock, 0);
			//Grid.SetRow(pinCheckBox, 1);
			//Grid.SetRow(naviStackPanel, 2);
			//Grid.SetRow(sendenButton, 2);

			//Grid.SetColumn(naviStackPanel, 1);

			//Grid.SetColumnSpan(infoTextBlock, 2);

			//infoGrid.Children.Add(infoTextBlock);
			//infoGrid.Children.Add(pinCheckBox);
			//infoGrid.Children.Add(sendenButton);
			//infoGrid.Children.Add(naviStackPanel);
			SupportEMailControl ctrl = new SupportEMailControl();
		    ctrl.SenderName = String.Format("{0} {1}", BeWoApp.LoggedOnEmployee.FirstName, BeWoApp.LoggedOnEmployee.LastName);
		    if (BeWoApp.LoggedOnEmployee.ContactInformations != null)
		    {
			    foreach (var contact in BeWoApp.LoggedOnEmployee.ContactInformations)
			    {
				    if (contact.ContactType == ContactType.business_Mail)
				    {
					    ctrl.SenderEMail = contact.ContactValue;
				    }
			    }
			    
		    }

		    ctrl.CancelButtonClicked += delegate
		    {
			    bewoWindow.Close();
		    };

			ctrl.OkButtonClicked += delegate
			{
				string nachricht = ctrl.Message;
				nachricht = String.Format("Supportanfrage von {0} <{1}>:\n\n{2}", ctrl.SenderName, ctrl.SenderEMail, nachricht);
				if (ctrl.CheckBoxSupportPin.IsChecked.HasValue && ctrl.CheckBoxSupportPin.IsChecked.Value)
				{
					nachricht += string.Format("\n\nPIN: {0}", GeneratePIN());
				}

				EMailVersenden(ctrl.SenderName, ctrl.SenderEMail, ctrl.Subject, nachricht, bewoWindow);
			};

		    bewoWindow.GroupBoxContent = ctrl;
			bewoWindow.rootGroupBox.Header = "E-Mail versenden";
			bewoWindow.Owner = BeWoApp.CurrentBeWo.MainWindow;
			bewoWindow.Show();
		}

		private void EMailVersenden(string senderName, string senderEMail, string betreff, string nachricht, BeWoWindow window)
		{
			var result = ServiceFacade.DoMailServiceSync(m => m.SendEMailWithSender(senderName, senderEMail, betreff, nachricht));
			
			if (result)
			{
				window.Close();
				MessageBox.Show("Die E-Mail  wurde erfolgreich versendet.", "E-Mail senden", MessageBoxButton.OK,
					MessageBoxImage.Information);
			}
			else
			{
				MessageBox.Show("Die E-Mail konnte leider nicht gesendet werden", "E-Mail senden", MessageBoxButton.OK,
					MessageBoxImage.Error);
			}
			
		}

		private void CreateSupportRequestWindow()
		{
			BeWoWindow bewoWindow = BeWoWpfUtils.CreateBeWoPopupWindow(withDynamicSize: true);

			#region PIN Erzeugen

			var grid = new Grid
			{
				Width = 300d,
				Background = (LinearGradientBrush) FindResource("ObjectEditBackgroundBrush")
			};

			var label1 = new Label {Content = "Ihre PIN lautet:", HorizontalAlignment = HorizontalAlignment.Center};
			var boldLabel = new Label
			{
				Content = "",
				FontWeight = FontWeights.Bold,
				HorizontalAlignment = HorizontalAlignment.Center
			};
			var label3 = new Label
			{
				Content = "Bitte geben Sie diese PIN beim Support-Anruf an",
				HorizontalAlignment = HorizontalAlignment.Center
			};

			var cancelButton = new Button {Content = "Schließen"};
			cancelButton.Click += delegate { bewoWindow.Close(); };

			var centeredStackPanel = new StackPanel
			{
				Orientation = Orientation.Vertical,
				VerticalAlignment = VerticalAlignment.Center,
				HorizontalAlignment = HorizontalAlignment.Center
			};
			centeredStackPanel.Children.Add(label1);
			centeredStackPanel.Children.Add(boldLabel);
			centeredStackPanel.Children.Add(label3);
			centeredStackPanel.Children.Add(cancelButton);

			grid.Children.Add(centeredStackPanel);

			#endregion

			#region InfoText

			var infoTextBlock = new TextBlock
			{
				Text = _PINInfoText,
				Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0)),
				Margin = new Thickness(3),
				TextWrapping = TextWrapping.Wrap,
				TextAlignment = TextAlignment.Center,
				VerticalAlignment = VerticalAlignment.Center
			};

			var infoGrid = new Grid
			{
				Background = (LinearGradientBrush) FindResource("ObjectEditBackgroundBrush")
			};
			var pinErzeugenButton = new Button {Content = "PIN erzeugen", Margin = new Thickness(3)};

			infoGrid.RowDefinitions.Add(new RowDefinition {Height = new GridLength(1, GridUnitType.Star)});
			infoGrid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});

			Grid.SetRow(infoTextBlock, 0);
			Grid.SetRow(pinErzeugenButton, 1);

			infoGrid.Children.Add(infoTextBlock);
			infoGrid.Children.Add(pinErzeugenButton);

			pinErzeugenButton.Click += delegate
			{
				bewoWindow.GroupBoxContent = grid;
				boldLabel.Content = GeneratePIN();
			};

			#endregion

			bewoWindow.GroupBoxContent = infoGrid;
			bewoWindow.rootGroupBox.Header = "Support";
			bewoWindow.Owner = BeWoApp.CurrentBeWo.MainWindow;
			bewoWindow.Show();
		}

		private static string GeneratePIN(int maxSize = 5)
		{
			var data = new byte[1];
			var crypto = new RNGCryptoServiceProvider();
			var result = new StringBuilder(maxSize);

			char[] chars = "ABCDEFGHJKLMNPQRSTUVWXYZ123456789".ToCharArray();
			crypto.GetBytes(data);
			data = new byte[maxSize];
			crypto.GetBytes(data);

			foreach (byte b in data)
				result.Append(chars[b%(chars.Length)]);

			var pin = new SupportPinDC
			{
				Pin = result.ToString(),
				IsUsed = false,
				CreationDate = DateTime.Now
			};
			pin.ExpirationDate = pin.CreationDate.Value.AddDays(3);

			ServiceFacade.DoUserServiceAsync(p =>
			{
				long res = -1;

				while (res == -1L)
				{
					pin = new SupportPinDC
					{
						Pin = result.ToString(),
						IsUsed = false,
						CreationDate = DateTime.Now
					};
					pin.ExpirationDate = pin.CreationDate.Value.AddDays(3);

					res = p.InsertNewSupportPin(pin);
				}
			}, false);

			return result.ToString();
		}

		private void button_Template_Click(object sender, RoutedEventArgs e)
		{
			if (DoSaveCheck())
			{
				NavigateTo(new WordDocumentTemplateView(TableID.Mandator, 1));
			}
		}

		private void UIElement_OnMouseEnter(object sender, MouseEventArgs e)
		{
			AufOffeneTerminePruefen();
		}

		public void InitOffeneTermine()
		{
			if (!_TermineInitialized && BeWoApp.LoggedOnEmployee != null)
			{
				AufOffeneTerminePruefen();
				_TermineInitialized = true;
			}
		}

		public void AufOffeneTerminePruefen()
		{
			if (BeWoApp.LoggedOnEmployee != null && BeWoApp.LoggedOnEmployee.EmployeeOid != null && BeWoApp.AppSettings.IsSchedulerAllowed)
				ServiceFacade.DoResourceServiceAsync(rs => rs.GetAllOpenAppointmentsForEmployee(BeWoApp.LoggedOnEmployee.EmployeeOid.Value), r => this.Dispatch(delegate
				{
					if (r.Count == 0)
					{
						HatNeueTermine = false;
						return;
					}

					HatNeueTermine = true;
				}), false);
		}

		private void ToolbarContent_OnLoaded(object sender, RoutedEventArgs e)
		{
			InitOffeneTermine();
		}
	}
}