using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;
using BeWo.Core;
using BeWo.Core.Config;
using BeWo.ServiceProxy;
using BeWo.View;
using BeWo.View.Navigation;
using BS.Shared;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;
using DevExpress.Xpf.Grid;

namespace BeWo
{
	/// <summary>
	///     Interaction logic for App.xaml
	/// </summary>
	public partial class BeWoApp : Application, INotifyPropertyChanged
	{
		private static FrameworkElement _lockedContent;

		public static LoginControl LoginControl;

		public static MainControl MainControl;

		//public static string Version = "Version 2.0";

		public static string Version = "Version 2.3";

		public static int RenderTier = 0;

		internal static string IpAddress = string.Empty;

		internal static string Tenant = string.Empty;

		internal static string ServerName = string.Empty;

		internal static string UserName = string.Empty;

		internal static string UserPassword = string.Empty;

		private static AppSettings _AppSettings;

	    private static CompactEmployeeDC _CompactLoggedOnEmployee;
		private static EmployeeDC _LoggedOnEmployee;

		private static UserDC _LoggedOnUser;

		private static MandatorDC _Mandator;
		private static string _ServerAddress;
		private static int _LockUITime = 30;
		private static List<Window> OpenDevExpressEditForms = new List<Window>();

        private static DocumentWatcher _DocumentWatcher;

		public static BeWoApp CurrentBeWo
		{
			get { return Current as BeWoApp; }
		}

		public static Dictionary<string, string> ICD10Diagnosis { get; set; }

		public static EmployeeDC LoggedOnEmployee
		{
			get { return _LoggedOnEmployee; }

			set { _LoggedOnEmployee = value; }
		}

	    public static CompactEmployeeDC CompactLoggedOnEmployee
	    {
            get { return _CompactLoggedOnEmployee; }

            set { _CompactLoggedOnEmployee = value; }
	    }

		public ObservableCollection<UserRightType> LoggedOnUsersRights
		{
			get
			{
				if (LoggedOnUser != null)
					return LoggedOnUser.GetGrantedRights().ToObservableCollection();
				return null;
			}
		}

        public DocumentWatcher DocumentWatcher
        {
            get
            {
                if (_DocumentWatcher == null)
                {
                    _DocumentWatcher = new DocumentWatcher();
                }

                return _DocumentWatcher;
            }
        }

		public static string ServerAddress
		{
			get { return _ServerAddress; }

			set
			{
				//if (_ServerAddress != null && _ServerAddress.Equals(value))
				//    return;
				_ServerAddress = value;
				ServiceFacade.UpdateServerAddresses(SiteOfOrigin.ToString());
			}
		}

		public static AppSettings AppSettings
		{
			get
			{
				if (_AppSettings == null)
				{
					RestoreAppSettings();
				}

				return _AppSettings;
			}
		}

		internal static UserDC LoggedOnUser
		{
			get { return _LoggedOnUser; }

			set
			{
				_LoggedOnUser = value;
				if (_LoggedOnUser != null)
				{
					var settings = _LoggedOnUser.Settings;

					ServiceFacade.DoEmployeeServiceAsync(s => s.LoadEmployee(value.Employee.EmployeeOid),
						r =>
						{
							_LoggedOnEmployee = r;

                            ServiceFacade.DoEmployeeServiceAsync(s => s.LoadCompactEmployee(value.Employee.EmployeeOid), r2 => { _CompactLoggedOnEmployee = r2; });

							if (MainControl != null)
							{
								MainControl.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
									(Action) (() => MainControl.InitOffeneTermine()));
							}
						});
				}

				CurrentBeWo.FirePropertyChanged("LoggedOnUsersRights");
			}
		}

		internal static MandatorDC Mandator
		{
			get { return _Mandator; }

			set
			{
				_Mandator = value;

			    bool showDatevFields                         = false;
			    bool isServiceRecordNoticeMandatory          = true;
                bool isPasswordSecurityActiv                 = false;
			    bool showServiceRecordsDistanceFields        = false;
			    bool showCustomerDistanceFields              = false;
			    bool showAdditionalService                   = false;
			    bool showRoundedDurationInEmployeeAnalysis   = true;
			    bool showTeamNews                            = false;
			    bool showMarker                              = false;
			    bool showAnnualReport                        = false;
			    bool showResources                           = true;
			    int maxDaysEditServiceRecordsAllowed         = 0;
                int hilfeplanAuslaufAuswahl                  = 3;
                int anzTageZeiterfassErfolgt                 = 0;
			    bool printerSettingsUseLandscape             = false;
			    bool printerSettingsUseMargins               = false;
			    bool printerSettingsUsePaperKind             = false;
                var hideServiceRecordInsertedByAndInsertedOn = false;
                bool isEndDateVisible                        = false;

				AppSettings.ShowAdvisedAttendedFlag = false;
				String timeRecordingMenuName = "Zeiterfassung";

				if (_Mandator != null)
				{
					string val = GetSettingValue(_Mandator.Settings, "ShowMedication");
					AppSettings.IsMedicationAllowed = val != null && val.Equals("1");

					val = GetSettingValue(_Mandator.Settings, "ShowScheduler");
					AppSettings.IsSchedulerAllowed = val != null && val.Equals("1");

					val = GetSettingValue(_Mandator.Settings, "ShowWohnheime");
					AppSettings.IsWohnheimAllowed = val != null && val.Equals("1");

					val = GetSettingValue(_Mandator.Settings, "IsServiceRecordNoticeMandatory");
					if (val != null && val.Equals("0"))
					{
						isServiceRecordNoticeMandatory = false;
					}
                    
                    val = GetSettingValue(_Mandator.Settings, "IsPasswordSecurityActiv");
                    if (val != null && val.Equals("1"))
                    {
                        isPasswordSecurityActiv = true;
                    }

                    val = GetSettingValue(_Mandator.Settings, "IsEndDateVisible");
                    if (val != null && val.Equals("1"))
                    {
                        isEndDateVisible = true;
                    }


					val = GetSettingValue(_Mandator.Settings, "MaxDaysEditServiceRecordsAllowed");
					int result;
					if (Int32.TryParse(val, out result))
					{
						maxDaysEditServiceRecordsAllowed = result;
					}

                    val = GetSettingValue(_Mandator.Settings, "HilfeplanAuslaufAuswahl");
                    int resultplan;
                    if (Int32.TryParse(val, out resultplan))
                    {
                        hilfeplanAuslaufAuswahl = resultplan;
                    }


                    val = GetSettingValue(_Mandator.Settings, "AnzTageZeiterfassErfolgt");
                    int resultzeitplan;
                    if (Int32.TryParse(val, out resultzeitplan))
                    {
                        anzTageZeiterfassErfolgt = resultzeitplan;
                    }

					val = GetSettingValue(_Mandator.Settings, "ShowDistanceFields");
					if (val != null && val.Equals("1"))
					{
						showServiceRecordsDistanceFields = true;
					}

					val = GetSettingValue(_Mandator.Settings, "ShowResources");
					if (val != null && val.Equals("0"))
					{
						showResources = false;
					}

					val = GetSettingValue(_Mandator.Settings, "ShowTeamNews");
					if (val != null && val.Equals("1"))
					{
						showTeamNews = true;
					}

					val = GetSettingValue(_Mandator.Settings, "ShowMarker");
					if (val != null && val.Equals("1"))
					{
						showMarker = true;
					}

					val = GetSettingValue(_Mandator.Settings, "ShowAnnualReport");
					if (val != null && val.Equals("1"))
					{
						showAnnualReport = true;
					}
					val = GetSettingValue(_Mandator.Settings, "ShowCustomerDistanceFields");
					if (val != null && val.Equals("1"))
					{
						showCustomerDistanceFields = true;
					}
					val = GetSettingValue(_Mandator.Settings, "ShowAdditionalService");
					if (val != null && val.Equals("1"))
					{
						showAdditionalService = true;
					}
					val = GetSettingValue(_Mandator.Settings, "ShowRoundedDurationInEmployeeAnalysis");
					if (val != null && val.Equals("0"))
					{
						showRoundedDurationInEmployeeAnalysis = false;
					}
					val = GetSettingValue(_Mandator.Settings, "ShowDatevFields");
					if (val != null && val.Equals("1"))
					{
						showDatevFields = true;
					}
					val = GetSettingValue(_Mandator.Settings, "PrinterSettingsUseLandscape");
					if (val != null && val.Equals("1"))
					{
						printerSettingsUseLandscape = true;
					}
					val = GetSettingValue(_Mandator.Settings, "PrinterSettingsUseMargins");
					if (val != null && val.Equals("1"))
					{
						printerSettingsUseMargins = true;
					}
					val = GetSettingValue(_Mandator.Settings, "PrinterSettingsUsePaperKind");
					if (val != null && val.Equals("1"))
					{
						printerSettingsUsePaperKind = true;
					}
                    val = GetSettingValue(_Mandator.Settings, "HideServiceRecordInsertedByAndInsertedOn");
				    if(val != null && val.Equals("1"))
				    {
                        hideServiceRecordInsertedByAndInsertedOn = true;
				    }

					switch (_Mandator.BeWoClientType)
					{
						case 1:
							//Die Kette
							showDatevFields = true;
							AppSettings.ShowAdvisedAttendedFlag = true;
							break;
						case 2:
							//Datev
							showDatevFields = true;
							break;
						case 3:
							////Köln Ring
							showDatevFields = true;
							timeRecordingMenuName = "Dokumentation";
							break;
						case 4:
							//Betreuwo
							break;

						case 5:
							//Kontakt und Krisenhilfe
							AppSettings.ShowLargeCustomerNotice = true;
							break;
						case 6:
							// Nur Jahresbericht
							break;
						case 7:
							//IBP
							showDatevFields = true;
							break;
						case 8:
							//LH Würzburg
							break;
						case 9:
							//Caritas Frankfurt+Aids Hilfe Gießen
							break;
						case 10:
							//Integra
							showDatevFields = true;
							break;
						case 11:
							//Hannover
							showDatevFields = true;
							break;
					}
				}

				AppSettings.ShowDatevFields                          = showDatevFields;
				AppSettings.IsServiceRecordNoticeMandatory           = isServiceRecordNoticeMandatory;
                AppSettings.IsPasswordSecurityActiv                  = isPasswordSecurityActiv;
                AppSettings.IsEndDateVisible                         = isEndDateVisible;  
				AppSettings.MaxDaysEditServiceRecordsAllowed         = maxDaysEditServiceRecordsAllowed;
                AppSettings.HilfeplanAuslaufAuswahl                  = hilfeplanAuslaufAuswahl;
                AppSettings.AnzTageZeiterfassErfolgt                 = anzTageZeiterfassErfolgt;
				AppSettings.TimeRecordingMenuName                    = timeRecordingMenuName;
				AppSettings.ShowDistanceFields                       = showServiceRecordsDistanceFields;
				AppSettings.ShowCustomerDistanceFields               = showCustomerDistanceFields;
				AppSettings.ShowAdditionalService                    = showAdditionalService;
				AppSettings.ShowRoundedDurationInEmployeeAnalysis    = showRoundedDurationInEmployeeAnalysis;
				AppSettings.ShowResources                            = showResources;
                AppSettings.HideServiceRecordInsertedByAndInsertedOn = hideServiceRecordInsertedByAndInsertedOn;
				AppSettings.ShowTeamNews                             = showTeamNews;
				AppSettings.ShowMarker                               = showMarker;
				AppSettings.ShowAnnualReport                         = showAnnualReport;
				AppSettings.PrinterSettingsUseLandscape              = printerSettingsUseLandscape;
				AppSettings.PrinterSettingsUseMargins                = printerSettingsUseMargins;
				AppSettings.PrinterSettingsUsePaperKind              = printerSettingsUsePaperKind;

                BS.Shared.Settings.ApplicationSettings.SupportConceptExpirationLimitInMonths = AppSettings.HilfeplanAuslaufAuswahl;
			}
		}

		internal static Uri SiteOfOrigin
		{
			get
			{
				String url = ServerAddress.ToLower();

#if DEBUG
				url = String.Format("http://localhost/Host");
				//url = String.Format("app1.bewoplaner.de/service");
#endif

				if (url.IndexOf("localhost") < 0)
				{
					int i;

					if (url.IndexOf("fortis") < 0)
					{
						if (Int32.TryParse(url, out i))
							url = "app" + url;

						if (url.IndexOf('.') < 0)
						{
							url += ".bewoplaner.de";
						}
					}
					if (url.IndexOf("/service") < 0)
					{
						url += "/service";
					}

					if (ServerAddress == "10.0.116.4") //LH Würzburg
						return new Uri(String.Format("http://{0}", url));
					return new Uri(String.Format("https://{0}", url));
				}
				return new Uri(url);
			}
		}

		public static int LockUITime
		{
			get
			{
				string lockTime = _Mandator.Settings.SplitToKeyValuePairList(";", "=").FirstOrDefault(f => f.Key.Equals("TimeUntilUILock")).Value;

				if (_LoggedOnUser != null && lockTime != null)
				{
					return Convert.ToInt32(lockTime);
				}
				return _LockUITime;
			}

			set
			{
				_LockUITime = value;

				if (_LoggedOnUser == null) return;

				AutoLockUI.LockUITime = value;
				AutoLockUI.StopTimer();
				AutoLockUI.StartAutoLockUIOption();
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public static string GetAndCreateUserAppDataPath()
		{
			try
			{
				string localAppData = Environment.GetFolderPath(
					Environment.SpecialFolder.LocalApplicationData);
				string companyFilePath
					= Path.Combine(localAppData, "beyondSoft");

				if (!Directory.Exists(companyFilePath))
					Directory.CreateDirectory(companyFilePath);

				string bewoFilePath
					= Path.Combine(companyFilePath, "BeWoPlaner");

				if (!Directory.Exists(bewoFilePath))
					Directory.CreateDirectory(bewoFilePath);

				return bewoFilePath;
			}
			catch (Exception ex)
			{
				MessageBox.Show(
					"Fehler beim Anlegen des Anwendungsordners. Sie besitzen nicht die erforderlichen Rechte, bitte wenden Sie sich an Ihren Systemadministrator.\n" +
					ex.Message, "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Exclamation);
			}
			return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		}

		public static string CreateNewSettingValue(string settings, string key, string val)
		{
			if (String.IsNullOrEmpty(settings))
			{
				return key + "=" + val;
			}

			string[] keyValuePairs = settings.Split(';');
			string newValue = string.Empty;
			foreach (string pair in keyValuePairs)
			{
				if (pair.IndexOf(key + "=") != 0)
				{
					if (newValue.Length > 0)
					{
						newValue += ";";
					}

					newValue += pair;
				}
			}

			if (newValue.Length > 0)
			{
				newValue += ";";
			}

			newValue += key + "=" + val;
			return newValue;
		}

		public static SettingsDC GetSettingValue(SettingsType pType)
		{
			if (_LoggedOnUser.Settings != null)
			{
				return _LoggedOnUser.Settings.FirstOrDefault(s => s.Type == pType);
			}

			return null;
		}

		public static string GetSettingValue(SettingsType pType, string key)
		{
			SettingsDC dc = GetSettingValue(pType);
			if (dc != null)
			{
				return GetSettingValue(dc.Value, key);
			}

			return null;
		}

		public static string GetSettingValue(string settings, string key)
		{
			if (!String.IsNullOrEmpty(settings))
			{
				if (settings.IndexOf(";") == -1 && settings.IndexOf("=") == -1)
				{
					return settings;
				}

				string[] keyValuePairs = settings.Split(';');

				return (from pair in keyValuePairs select pair.Split('=') into keyValuePair where keyValuePair.Length == 2 where keyValuePair[0] == key select keyValuePair[1]).FirstOrDefault();
			}

			return null;
		}

		public static void SetSettingValue(SettingsType pType, string key, string val)
		{
			var dc = GetSettingValue(pType);

			if (dc == null)
			{
				var newDc = new SettingsDC {Type = pType, Value = CreateNewSettingValue(string.Empty, key, val)};
				_LoggedOnUser.Settings.Add(newDc);
			}
			else
			{
				dc.Value = CreateNewSettingValue(dc.Value, key, val);
			}
		}

		internal static bool HasLoggedOnUserRight(UserRightType[] pRight)
		{
			if (LoggedOnUser != null)
			{
				return pRight == null || (pRight.Length == 1 && pRight[0] == UserRightType.None) || LoggedOnUser.GetGrantedRights().Exists(
					right =>
					{
						var rightAsString = pRight.ToString();
						var vals = rightAsString.Split(",");

						foreach (var urt in pRight)
						{
							if (urt == right)
							{
								return true;
							}
						}

						return false;
					});
			}

			return false;
		}

		internal static void SaveAppSettings()
		{
			if (_AppSettings != null && _LoggedOnUser != null && _AppSettings.IsDirty)
			{
				_AppSettings.IsDirty = false;
				SetSettingValue(SettingsType.ApplicationSettings, "WindowStateType", ((int) _AppSettings.WindowState).ToString());
				SetSettingValue(SettingsType.ApplicationSettings, "LastSelectedServiceRecordTimeInterval", ((int) _AppSettings.LastSelectedServiceRecordTimeInterval).ToString());
				SetSettingValue(SettingsType.ApplicationSettings, "NDays", _AppSettings.NDays.ToString());
				SetSettingValue(SettingsType.ApplicationSettings, "ShowAllClients", _AppSettings.ShowAllClients ? "1" : "0");
				SetSettingValue(SettingsType.ApplicationSettings, "ShowOnlyMySupportConcepts", _AppSettings.ShowOnlyMySupportConcepts ? "1" : "0");
				SetSettingValue(SettingsType.ApplicationSettings, "ShowOnlyMyClients", _AppSettings.ShowOnlyMyClients ? "1" : "0");
				SetSettingValue(SettingsType.ApplicationSettings, "ShowExpiredSupportConcepts", _AppSettings.ShowExpiredSupportConcepts ? "1" : "0");
				SetSettingValue(SettingsType.ApplicationSettings, "ShowServiceRecordGridControl", _AppSettings.ShowServiceRecordGridControl ? "1" : "0");
				SetSettingValue(SettingsType.ApplicationSettings, "StartupPanelMaximized", _AppSettings.StartupPanelMaximized);
                SetSettingValue(SettingsType.ApplicationSettings, "HideServiceRecordInsertedByAndInsertedOn", _AppSettings.HideServiceRecordInsertedByAndInsertedOn ? "1" : "0");
				SetSettingValue(SettingsType.ApplicationSettings, "DocumentationFontSize", _AppSettings.DocumentationFontSize.ToString());
                SetSettingValue(SettingsType.ApplicationSettings, "ZeigeNurMeineTermine", _AppSettings.ZeigeNurMeineTermine ? "1" : "0");

				string val = string.Empty;
				if (_AppSettings.StartupPanelOrder != null)
				{
					foreach (string item in _AppSettings.StartupPanelOrder)
					{
						if (val.Length > 0)
						{
							val += "|";
						}

						val += item;
					}
				}

				SetSettingValue(SettingsType.ApplicationSettings, "StartupPanelOrder", val);

				ServiceFacade.DoUserServiceAsync(s => s.UpdateUserSettings(_LoggedOnUser.UserOid.Value, _LoggedOnUser.Settings), ReloadSettings, false);
			}
		}

		internal static void ShowError(string message, Exception ex, bool showDetails)
		{
			if (MainControl != null)
			{
				MainControl.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() => MainControl.ShowControlAsModalPopUp(new ExceptionMessageBox(message, ex, showDetails))));
			}
			else if (LoginControl != null)
			{
				LoginControl.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() => LoginControl.ShowControlAsModalPopUp(new ExceptionMessageBox(message, ex, showDetails))));
			}
			else
			{
				MessageBox.Show(message + "\n\n" + ex);
			}
		}


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

		public static void InitAutoUILocking()
		{
			EventManager.RegisterClassHandler(typeof (Window), UIElement.PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));
			EventManager.RegisterClassHandler(typeof (Window), UIElement.PreviewKeyDownEvent, new KeyEventHandler(OnPreviewKeyDown));

			IEnumerable<KeyValuePair<string, string>> settingsKVPList = _Mandator.Settings.SplitToKeyValuePairList(";", "=");

			string x = settingsKVPList.FirstOrDefault(f => f.Key.Equals("TimeUntilUILock")).Value ?? "NULL";
			int y = _LockUITime;

			AutoLockUI.LockUITime = Convert.ToInt32(settingsKVPList.FirstOrDefault(f => f.Key.Equals("TimeUntilUILock")).Value ?? LockUITime.ToString());


			AutoLockUI.DoAutoLockUIEvent += AutoLockUIDoAutoLockUIEvent;
			AutoLockUI.StartAutoLockUIOption();
		}

		protected override void OnStartup(StartupEventArgs e)
		{
			//Licenser.LicenseKey = "DGF20-AUTJ7-3K8MD-DNNA";
			DataControlBase.AllowInfiniteGridSize = true;
			//Timeline.DesiredFrameRateProperty.OverrideMetadata(typeof(Timeline),
			//    new FrameworkPropertyMetadata { DefaultValue = 30 });

			RenderTier = RenderCapability.Tier >> 16;

			base.OnStartup(e);
			//AppDomain.CurrentDomain.UnhandledException += (s, ex) => ShowError(null, ex.ExceptionObject as Exception, true);

			Dispatcher.UnhandledException += (s, ex)
				=>
			{
				if (ex.Exception == null || String.IsNullOrEmpty(ex.Exception.Message) || !ex.Exception.ToString().Contains("DevExpress.Xpf.Bars.Customization.CustomizationControl.OnLoaded"))
				{
					ShowError(null, ex.Exception, true);
				}
				ex.Handled = true;
			};

			FrameworkElement.LanguageProperty.OverrideMetadata(typeof (FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
		}

		private static void ReloadSettings(List<SettingsDC> settings)
		{
			if (_LoggedOnUser != null)
				_LoggedOnUser.Settings = settings;
		}

		private static AppSettings RestoreAppSettings()
		{
			if (_LoggedOnUser != null)
			{
				_AppSettings = new AppSettings();
				List<SettingsDC> settings = _LoggedOnUser.Settings;

				string val = GetSettingValue(SettingsType.ApplicationSettings, "WindowStateType");
				int result;
				if (Int32.TryParse(val, out result))
				{
					_AppSettings.WindowState = (AppSettings.WindowStateType) result;
				}

				val = GetSettingValue(SettingsType.ApplicationSettings, "LastSelectedServiceRecordTimeInterval");
				if (Int32.TryParse(val, out result))
				{
					_AppSettings.LastSelectedServiceRecordTimeInterval = (ServiceRecordTimeInterval) result;
				}

				val = GetSettingValue(SettingsType.ApplicationSettings, "ShowAllClients");
				_AppSettings.ShowAllClients = val == "1";

				val = GetSettingValue(SettingsType.ApplicationSettings, "ShowOnlyMySupportConcepts");
				_AppSettings.ShowOnlyMySupportConcepts = val != "0";

				val = GetSettingValue(SettingsType.ApplicationSettings, "ShowOnlyMyClients");
				_AppSettings.ShowOnlyMyClients = val == "1";

				val = GetSettingValue(SettingsType.ApplicationSettings, "ShowServiceRecordGridControl");
				_AppSettings.ShowServiceRecordGridControl = val == "1";

				val = GetSettingValue(SettingsType.ApplicationSettings, "ShowExpiredSupportConcepts");
				_AppSettings.ShowExpiredSupportConcepts = val != "0";

				val = GetSettingValue(SettingsType.ApplicationSettings, "StartupPanelOrder");

				_AppSettings.StartupPanelMaximized = GetSettingValue(SettingsType.ApplicationSettings, "StartupPanelMaximized");

				_AppSettings.DocumentationFontSize = Convert.ToDouble(GetSettingValue(SettingsType.ApplicationSettings, "DocumentationFontSize"));

			    _AppSettings.ZeigeNurMeineTermine = GetSettingValue(SettingsType.ApplicationSettings, "ZeigeNurMeineTermine") == "1";

				_AppSettings.NDays = Convert.ToInt32(GetSettingValue(SettingsType.ApplicationSettings, "NDays"));

				if (val != null)
				{
					_AppSettings.StartupPanelOrder = new List<string>();
					string[] panels = val.Split(new[] {'|'});
					foreach (string item in panels)
					{
						_AppSettings.StartupPanelOrder.Add(item);
					}
				}
				_AppSettings.IsDirty = false;
			}

			return _AppSettings;
		}

		private void btnOpenServiceRecordView_Click(object sender, RoutedEventArgs e)
		{
			var btn = sender as Button;
			if (btn == null) return;

			var dc = btn.Tag as CompactSupportConceptDC;

			if (dc == null) return;

			if (MainControl != null)
				MainControl.NavigateToServiceRecordView(dc.SupportConceptOid);
		}

		private void togglebutton_maximise_Checked(object sender, RoutedEventArgs e)
		{
			if (MainControl != null)
				MainControl.Maximize();
		}

		private void togglebutton_maximise_Unchecked(object sender, RoutedEventArgs e)
		{
			if (MainControl != null)
				MainControl.Minimize();
		}

		private void FrameLeftMouseDown(object sender, MouseButtonEventArgs e)
		{
			var border = (Border) sender;
			var borderParent = (Grid) border.Parent;
			DependencyObject template = borderParent.TemplatedParent;
			var parent = new Window();

			var x = (FrameworkElement) template;
			if (x != null)
			{
				var y = new FrameworkElement();
				while (y != null)
				{
					y = (FrameworkElement) x.Parent;
					if (y != null)
						x = y;
				}

				if (x is Window)
				{
					parent = (Window) x;
					parent.DragMove();
				}
			}
		}

		private static void AutoLockUIDoAutoLockUIEvent()
		{
		    if (UserName.Equals("BSAdmin"))
		    {
                AutoLockUI.StartAutoLockUIOption();
                return;
		    }

			if (CurrentBeWo.MainWindow.Content is LockedPage)
			{
				AutoLockUI.StartAutoLockUIOption();
				return;
			}

			_lockedContent = CurrentBeWo.MainWindow.Content as FrameworkElement;

			if (_lockedContent is Grid && (_lockedContent as Grid).Children.Contains(LoginControl))
			{
				AutoLockUI.StartAutoLockUIOption();
				return;
			}

			WindowCollection fenster = CurrentBeWo.Windows;
			OpenDevExpressEditForms = (from Window x in fenster where !x.Title.Equals("BeWoPlaner") || x.GetType() != typeof (MainWindow) select x).ToList();


			OpenDevExpressEditForms.ForEach(fe => fe.Close());

			var lockedPage = new LockedPage();
			lockedPage.ButtonLogin.Click += UnlockBeWoPlaner;

			CurrentBeWo.MainWindow.Content = lockedPage;
			CurrentBeWo.MainWindow.Focus();

			AutoLockUI.StartAutoLockUIOption();
		}

		private static void UnlockBeWoPlaner(object sender, RoutedEventArgs e)
		{
			var lbtn = (Button) sender;

			var lbtnParent = (Grid) lbtn.Parent;
			var mainWindowUIElements = new UIElement[lbtnParent.Children.Count];
			lbtnParent.Children.CopyTo(mainWindowUIElements, 0);

			List<UIElement> elementList = mainWindowUIElements.ToList();
			string username = ((TextBox) elementList.Where(el => el is TextBox && ((TextBox) el).Name.Equals("TextBoxUsername")).ToList()[0]).Text;
			string password = ((PasswordBox) elementList.Where(el => el is PasswordBox && ((PasswordBox) el).Name.Equals("PasswordBoxPassword")).ToList()[0]).Password;

			if (String.IsNullOrEmpty(username) || !username.Equals(_LoggedOnUser.LoginName, StringComparison.OrdinalIgnoreCase))
			{
				MessageBox.Show("Das Programm kann nur vom Benutzer '" + _LoggedOnUser.LoginName + "' entsperrt werden.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
				return;
			}

			ServiceFacade.DoUserServiceAsync(u => u.IsUserValid(username, password, ""), r =>
			{
				if (!r.Equals(UserValidationResult.UserValid))
				{
					MessageBox.Show("Anmeldeinformationen nicht bekannt. Bitte überprüfen Sie den Benutzernamen und das Passwort!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
					return;
				}

				Current.Dispatch(delegate
				{
					CurrentBeWo.MainWindow.Content = _lockedContent;
					foreach (Window form in OpenDevExpressEditForms)
					{
						try
						{
							form.Show();
						}
						catch (Exception)
						{
						}
					}
				});
			}, true);
		}

		private static void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
		{
			AutoLockUI.ResetLockUITimer();
		}

		private static void OnPreviewKeyDown(object sender, KeyEventArgs e)
		{
			AutoLockUI.ResetLockUITimer();
		}

		private void Hyperlink_Hilfeplan_Reaktivieren_Click(object sender, RoutedEventArgs e)
		{
			var scNavView = (SupportConceptNavigationView) MainControl.ActiveView;

			if (scNavView != null)
			{
				var supportConcept = (CompactSupportConceptDC) ((Hyperlink) sender).Tag;
				scNavView.MainNavigationView_OnReactivateObject(supportConcept);
			}
		}
	}
}