using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;

using BeWo.Annotations;
using BeWo.Core;
using BeWo.Core.Service;
using BeWo.Scheduler.Converter;
using BeWo.Scheduler.ViewModel;
using BeWo.ServiceProxy;

using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;
using DevExpress.Utils;
using DevExpress.Xpf.Bars;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Scheduler;
using DevExpress.Xpf.Scheduler.Drawing;
using DevExpress.Xpf.Scheduler.Reporting;
using DevExpress.XtraScheduler;
using Appointment    = DevExpress.XtraScheduler.Appointment;
using ColorConverter = System.Windows.Media.ColorConverter;
using SchedulerControl = DevExpress.Xpf.Scheduler.SchedulerControl;


namespace BeWo.Scheduler.View
{
	public partial class NewSchedulerView : INotifyPropertyChanged
	{
	    private bool _IsEmployeeBrushVisible;

	    public bool IsEmployeeBrushVisible
	    {
	        get { return _IsEmployeeBrushVisible; }

	        set
	        {
	            _IsEmployeeBrushVisible = value;
	            OnPropertyChanged("IsEmployeeBrushVisible");
	        }
	    }

	    public bool IsInCustomerViewMode { get; set; }

		public event PropertyChangedEventHandler PropertyChanged;

		SchedulerPrintingSettings printingSettings = new SchedulerPrintingSettings();

		public NewSchedulerViewModel ViewModel { get; set; }

		[NotifyPropertyChangedInvocator]
		protected void OnPropertyChanged(string propertyName)
		{
			var handler = PropertyChanged;
			if (handler != null)
				handler(this, new PropertyChangedEventArgs(propertyName));
		}

	    public bool ZeigeNurMeineTermine
	    {
	        get { return BeWoApp.AppSettings.ZeigeNurMeineTermine; }
	        set
	        {
                if (BeWoApp.AppSettings.ZeigeNurMeineTermine != value)
	            {
                    BeWoApp.AppSettings.ZeigeNurMeineTermine = value;
                    BeWoApp.SaveAppSettings();
                    OnPropertyChanged("ZeigeNurMeineTermine");
	            }
	        }
	    }

		private List<CompactEmployeeDC> _AllEmployees;
		public List<CompactEmployeeDC> AllEmployees
		{
		    get
		    {
		        return _AllEmployees ?? (_AllEmployees = new List<CompactEmployeeDC>());
		    }

			set
			{
			    if (!Equals(_AllEmployees, value))
			    {
                    _AllEmployees = value;

                    OnPropertyChanged("AllEmployees");
			    }
			}
		}

		private List<CompactEmployeeDC> _GefilterteMitarbeiter;
		public List<CompactEmployeeDC> GefilterteMitarbeiter
		{
			get
			{
				return _GefilterteMitarbeiter ?? (_GefilterteMitarbeiter = new List<CompactEmployeeDC>(AllEmployees));
			}

			set 
			{
			    if (!Equals(_GefilterteMitarbeiter, value))
			    {
                    _GefilterteMitarbeiter = value;
			        _GefilterteMitarbeiter.Sort((x, y) => String.Compare((x.LastName + ", " + x.FirstName), y.LastName + ", " + y.FirstName, StringComparison.Ordinal));

                    OnPropertyChanged("GefilterteMitarbeiter"); 
			    }
			}
		}

		private List<CompactCustomerDC> _GefilterteKlienten;
		public List<CompactCustomerDC> GefilterteKlienten
		{
		    get
		    {
		        return _GefilterteKlienten ?? (_GefilterteKlienten = new List<CompactCustomerDC>(AllCustomers));
		    }

			set
			{
			    if (!Equals(_GefilterteKlienten, value))
			    {
			        _GefilterteKlienten = value;
			        _GefilterteKlienten.Sort((x, y) => String.Compare((x.LastName + ", " + x.FirstName), y.LastName + ", " + y.FirstName, StringComparison.Ordinal));

			        OnPropertyChanged("GefilterteKlienten");
			    }
			}
		}

		private List<CompactCustomerDC> _AllCustomers;
		public List<CompactCustomerDC> AllCustomers
		{
		    get
		    {
		        return _AllCustomers ?? (_AllCustomers = new List<CompactCustomerDC>());
		    }

			set
			{
			    if (!Equals(_AllCustomers, value))
			    {
			        _AllCustomers = value;
			        OnPropertyChanged("AllCustomers");
			    }
			}
		}

		private List<ResourceDC> _AllResources;
		public List<ResourceDC> AllResources
		{
		    get
		    {
		        return _AllResources ?? (_AllResources = new List<ResourceDC>());
		    }

			set
			{
			    if (!Equals(_AllResources, value))
			    {
			        _AllResources = value;
			        OnPropertyChanged("AllResources");
			    }
			}
		}

		private List<CompactCustomerDC> _CustomerList;
		public List<CompactCustomerDC> CustomerList
		{
		    get
		    {
		        return _CustomerList ?? (_CustomerList = new List<CompactCustomerDC>());
		    }

			set
			{
			    if (!Equals(_CustomerList, value))
			    {
			        _CustomerList = value;
			        _CustomerList.Sort((x, y) => String.Compare((x.LastName + ", " + x.FirstName), y.LastName + ", " + y.FirstName, StringComparison.Ordinal));
			        OnPropertyChanged("CustomerList");
			    }
			}
		}

		private int timelineDayCount;
		private SchedulerViewType currentViewType;

		private Dictionary<ValueListEntryDC, List<ResourceDC>> _Category2ResourcesDictionary;
		public Dictionary<ValueListEntryDC, List<ResourceDC>> Category2ResourcesDictionary
		{
		    get
		    {
		        return _Category2ResourcesDictionary ?? (_Category2ResourcesDictionary = new Dictionary<ValueListEntryDC, List<ResourceDC>>());
		    }

		    set
		    {
		        if (!Equals(_Category2ResourcesDictionary, value))
		        {
		            _Category2ResourcesDictionary = value;

                    AllResources = new List<ResourceDC>();
		            value.DoForEach(d => AllResources.AddRange(d.Value));

                    OnPropertyChanged("Category2ResourcesDictionary");
		        }
		    }
		}

		private List<CompactEmployeeDC> _SelectedEmployees = new List<CompactEmployeeDC>();
		private List<CompactCustomerDC> _SelectedCustomers = new List<CompactCustomerDC>();
		private List<ResourceDC> _SelectedResources = new List<ResourceDC>();

		public List<CompactEmployeeDC> SelectedEmployees
		{
			get { return _SelectedEmployees; }
			set
			{
				_SelectedEmployees = value;
				_SelectedEmployees.Sort((x, y) => String.Compare((x.LastName + ", " + x.FirstName), y.LastName + ", " + y.FirstName, StringComparison.Ordinal));
				if (value.Equals(AllEmployees))
				{
				    AlleMitarbeiterCB.IsChecked = true;
				}

                ZeigeNurMeineTermine = value.Count == 1 && value.Contains(BeWoApp.CompactLoggedOnEmployee);

				OnPropertyChanged("SelectedEmployees");
				OnPropertyChanged("SelectedItems");
			}
		}

		public List<CompactCustomerDC> SelectedCustomers
		{
			get { return _SelectedCustomers; }
			set
			{
				_SelectedCustomers = value;
				_SelectedCustomers.Sort((x, y) => String.Compare((x.LastName + ", " + x.FirstName), y.LastName + ", " + y.FirstName, StringComparison.Ordinal));
				if (NurMeineKlientenCB.IsChecked.HasValue && NurMeineKlientenCB.IsChecked.Value && value.Equals(GefilterteKlienten) || value.Equals(AllCustomers))
				{
				    AlleKlientenCB.IsChecked = true;
				}

				OnPropertyChanged("SelectedCustomers");
				OnPropertyChanged("SelectedItems");
			}
		}

		public List<ResourceDC> SelectedResources
		{
			get { return _SelectedResources; }
			set
			{
				_SelectedResources = value;
				if (value.Equals(AllResources))
				{
				    AlleRessourcenCB.IsChecked = true;
				}

				OnPropertyChanged("SelectedResources");
				OnPropertyChanged("SelectedItems");
			}
		}

		public IEnumerable<IDataContract> SelectedItems
		{
			get
			{
				var erg = new List<IDataContract>();
				erg.AddRange(SelectedEmployees);
				erg.AddRange(SelectedCustomers);
				erg.AddRange(SelectedResources);

				return erg;
			}
		}

		public IEnumerable<IDataContract> AllItems
		{
			get
			{
				var erg = new List<IDataContract>();
				erg.AddRange(GefilterteKlienten);
				erg.AddRange(AllResources);

				return erg;
			}
		}

		public static bool IgnoreChangeEvents;

		private List<CompactTeamDC> EmployeesTeams = new List<CompactTeamDC>();

		private string requests;
		public string Requests
		{
			get { return requests ?? (requests = string.Format("{0} Benaschrichtigungen", "keine")); }
			set
			{
				requests = value;
				OnPropertyChanged("Requests");
			}
		}

		public static TimeSpan FetchPadding = TimeSpan.FromDays(14);

		private TimeInterval lastFetchedInterval = new TimeInterval();

		public long CustomerOidToPreselect { get; set; }

		//private static string[] outlookCalendarPaths;
		//public static string[] OutlookCalendarPaths
		//{
		//	get
		//	{
		//		if (outlookCalendarPaths != null)
		//			return outlookCalendarPaths;

		//		try
		//		{
		//			outlookCalendarPaths = OutlookExchangeHelper.GetOutlookCalendarPaths();
		//		}
		//		catch
		//		{
		//			outlookCalendarPaths = new string[0];
		//		}

		//		return outlookCalendarPaths;
		//	}
		//}

		// KONSTRUKTOR
		public NewSchedulerView(long customerOid)
		{
			// Kalenderaufruf aus dem CustomerView2 heraus
			CustomerOidToPreselect = customerOid;
			ConstructObject();
		}

		public NewSchedulerView()
		{
			ConstructObject();
		}

        public static void SchedulerWriteLog(string info = "")
	    {
#if(DEBUG)
            using (var sw = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SchedulerLog.txt"), true))
            {
                sw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ffff") + " " + info);
            }
#endif
	    }

		private void ConstructObject()
		{
            //SchedulerWriteLog();

		    IsEmployeeBrushVisible = true;

			if (BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View) || BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAnsehen))
			{
				Cache.GetInstance().GetAllActiveEmployeesCompact(liste => this.Dispatch(() =>
				{
					AllEmployees = liste;
					GefilterteMitarbeiter = liste;
				}));
			}
			else
			{
			    CompactEmployeeDC compact = null;
                ServiceFacade.DoEmployeeServiceSync(s => compact = s.LoadCompactEmployee(BeWoApp.LoggedOnEmployee.EmployeeOid.Value));

                AllEmployees          = new List<CompactEmployeeDC> { compact };
                GefilterteMitarbeiter = new List<CompactEmployeeDC> { compact };
			}

			if (BeWoApp.LoggedOnUser.HasRight(UserRightType.Customer_ViewMyCustomers) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View))
			{
				var cusRels = BeWoApp.LoggedOnEmployee.RelatedCustomers;

				AllCustomers       = cusRels.Select(cr => cr.Customer).ToList();
				CustomerList       = AllCustomers;
				GefilterteKlienten = AllCustomers;
			}
			else
			{
				Cache.GetInstance().GetAllActiveCustomersCompact(liste => this.Dispatch(() =>
				{
					var erg = ((!BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderKliententermineAlleAnsehen)) ? liste.Where(c => c.IsRelatedToEmployee).ToList() : liste).Where(c => c.IsArchived == false).ToList();

					AllCustomers       = erg;
					CustomerList       = AllCustomers;
					GefilterteKlienten = AllCustomers;

					Scheduler.UpdateLayout();
				}));
			}

			Cache.GetInstance().GetCategories2ResourcesDictionary(dict => this.Dispatch(() =>
			{
			    Category2ResourcesDictionary = dict;
			}));

			ServiceFacade.DoEmployeeServiceSync(es => EmployeesTeams = es.GetTeamOidsByEmployee(BeWoApp.LoggedOnEmployee.EmployeeOid.Value));

			InitializeComponent();
			InitViewModel();
			InitScheduler();

			Scheduler.Storage.AppointmentStorage.ResourceSharing = false;

			DataContext = this;

			currentViewType = Scheduler.ActiveViewType;

			EditorLocalizer.Active = new GermanEditorLocalizer();

			InitRights();

			foreach (var item in from object item in TabControl.Items let ti = (TabItem)item where ti.Visibility.Equals(Visibility.Visible) select item)
			{
				TabControl.SelectedIndex = TabControl.Items.IndexOf(item);
				break;
			}
		}

		//private void Synchronize()
		//{
		//	var synchronizer = new OutlookExportSynchronizer(Scheduler.Storage.GetCoreStorage());
			
		//	if (OutlookCalendarPaths.Length <= 0) return;

		//	((ISupportCalendarFolders) synchronizer).CalendarFolderName = OutlookCalendarPaths[0];
		//	synchronizer.ForeignIdFieldName = "OutlookEntryId";

		//	synchronizer.AppointmentSynchronizing += (sender, args) =>
		//	{
				
		//	};

			
		//	synchronizer.Synchronize();
		//}

		private bool istErsterAufruf = true;

		#region InitViewModel
		private void InitViewModel()
		{
			ViewModel = new NewSchedulerViewModel();
			ViewModel.ViewModelChanged += ViewModel_ViewModelChanged;
			ViewModel.ViewModelChanged += UpdateRequestStringEvent;
		}

		private void ViewModel_ViewModelChanged(object sender, EventArgs<ISchedulerViewModel> e)
		{
			this.Dispatch(() =>
			{
				UpdateDataSource(e.Data);
			    if (istErsterAufruf)
			    {
			        if (MainControl.HatNeueTermine)
			        {
			            FensterOeffnen();
			        }

			        istErsterAufruf = false;
			    }
                else
                {
                    UpdateViewModelFilter();
                }
			});
		}

		private void InitScheduler()
		{
			Scheduler.Start                                            = DateTime.Now;
			timelineDayCount                                           = 0;
			Scheduler.DayView.NavigationButtonVisibility               = NavigationButtonVisibility.Always;
			Scheduler.DayView.AppointmentDisplayOptions.ShowRecurrence = true;
			Scheduler.DayView.AppointmentDisplayOptions.ShowReminder   = true;
			Scheduler.DayView.ResourcesPerPage                         = 3;

			Scheduler.WorkWeekView.ShowFullWeek               = false;
			Scheduler.WorkWeekView.ShowWorkTimeOnly           = false;
			Scheduler.WorkWeekView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
			Scheduler.WorkWeekView.ResourcesPerPage           = 3;

			Scheduler.WeekView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
			Scheduler.WeekView.ResourcesPerPage           = 3;

			Scheduler.MonthView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
			Scheduler.MonthView.ResourcesPerPage           = 3;

			Scheduler.TimelineView.NavigationButtonVisibility = NavigationButtonVisibility.Always;
			Scheduler.TimelineView.ResourcesPerPage           = 0;
		}

		private void InitRights()
		{
			MitarbieterTabItem.Visibility = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAnsehen) ? Visibility.Visible : Visibility.Collapsed;
			RessourcenTabItem.Visibility  = Visibility.Visible;

			MitarbeiterEbenenCheckBox.Visibility = MitarbieterTabItem.Visibility;
			RessourcenEbenenCheckBox.Visibility  = RessourcenTabItem.Visibility;
		}

		private void UpdateDataSource(ISchedulerViewModel vm)
        {
			UpdateCustomFieldMappings(vm);
            
			IgnoreChangeEvents = true;

			Scheduler.Storage.AppointmentStorage.DataSource = vm.Appointments;

			UpdateSchedulerSettings();

			foreach (var item in Scheduler.Storage.AppointmentStorage.Items)
			{
				var bapp = item.GetSourceObject(Scheduler.GetCoreStorage()) as IBeWoAppointment;

				if(item.IsRecurring) {
					var ausnahmen = item.GetExceptions();
					foreach (var exc in ausnahmen)
					{
						var b = exc.GetSourceObject(Scheduler.GetCoreStorage()) as IBeWoAppointment;
						if (b == null || b.CustomFields == null)
						{
						    continue;
						}

						foreach (var field in b.CustomFields)
						{
						    exc.CustomFields[field.Key] = field.Value;
						}
					}
				}

				if (bapp == null || bapp.CustomFields == null) continue;

				foreach (var field in bapp.CustomFields)
				{
				    item.CustomFields[field.Key] = field.Value;
				}
			}

			IgnoreChangeEvents = false;
		}

		private void UpdateSchedulerSettings()
		{
			var settings = ViewModel.GetActiveSettings();

			Scheduler.Start = settings.StartDate;
			var starttimeInterval = settings.StartDate.Date;
			starttimeInterval = starttimeInterval.AddHours(Scheduler.WorkWeekView.WorkTime.Start.Hours);
			settings.ViewType = ViewTypeConvert.ToAppointmentViewType(currentViewType);

			switch (settings.ViewType)
			{
				case AppointmentViewType.Day:
					Scheduler.ActiveViewType = SchedulerViewType.Day;
					Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0)));
					Scheduler.DayView.DayCount = settings.DayViewCount;
					break;
				case AppointmentViewType.Week:
					Scheduler.ActiveViewType = SchedulerViewType.Week;
					Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0)));
					break;
				case AppointmentViewType.Month:
					Scheduler.ActiveViewType = SchedulerViewType.Month;
					break;
				case AppointmentViewType.WorkWeek:
					Scheduler.ActiveViewType = SchedulerViewType.WorkWeek;
					Scheduler.ActiveView.GotoTimeInterval(new TimeInterval(starttimeInterval, new TimeSpan(8, 0, 0)));
					break;
				case AppointmentViewType.Timeline:
					Scheduler.ActiveViewType = SchedulerViewType.Timeline;
					Scheduler.TimelineView.ResourcesPerPage = settings.TimelineResourceCount;
					Scheduler.TimelineView.IntervalCount = settings.TimelineIntervalCount;
					break;
			}

			UpdateOptionPanel();

			try
			{
				Scheduler.GroupType = settings.GroupByResource ? SchedulerGroupType.Resource : SchedulerGroupType.None;

				Scheduler.OptionsCustomization.AllowAppointmentCreate = UsedAppointmentType.Custom;
				Scheduler.OptionsCustomization.AllowAppointmentDrag = UsedAppointmentType.Custom;
				Scheduler.OptionsCustomization.AllowAppointmentDelete = UsedAppointmentType.Custom;
				Scheduler.OptionsCustomization.AllowAppointmentEdit = UsedAppointmentType.Custom;
				Scheduler.OptionsCustomization.AllowAppointmentDragBetweenResources = UsedAppointmentType.Custom;
			}
			catch (Exception)
			{
				MessageBox.Show("Ein Fehler bei der Darstellung ist aufgetreten.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}

		private void UpdateCustomFieldMappings(ISchedulerViewModel vm)
		{
			Scheduler.Storage.AppointmentStorage.CustomFieldMappings.Clear();
			vm.AddCustomFieldsMapping(Scheduler.Storage);
		}
		#endregion

		public CheckBoxConverter CheckBoxConverter
		{
			get { return Resources["CheckBoxConverter"] as CheckBoxConverter; }
		}

		#region Filterauswahl
		private void AlleMitarbeiterCB_OnClick(object sender, RoutedEventArgs e)
		{
			var cb = (CheckBox) sender;
			if (!cb.IsChecked.HasValue) return;

			SelectedEmployees = cb.IsChecked.Value ? new List<CompactEmployeeDC>(AllEmployees) : new List<CompactEmployeeDC>();

            if(SelectedEmployees.Count > 1)
            {
                ZeigeNurMeineTermine = false;
            }

			Scheduler.ActiveView.LayoutChanged();
		}

		private void MitarbeiterListe_OnClick(object sender, RoutedEventArgs e)
		{
			var cb = (CheckBox) sender;
			var selectedEmployee = cb.DataContext as CompactEmployeeDC;

			if (CheckBoxConverter != null && selectedEmployee != null)
			{
			    CheckBoxConverter.AktuellerMitarbeiter = selectedEmployee;
			}
		}

		private void AlleRessourcenCB_OnClick(object sender, RoutedEventArgs e)
		{
			var cb = (CheckBox) sender;
			if (!cb.IsChecked.HasValue)
			{
			    return;
			}

			SelectedResources = cb.IsChecked.Value ? new List<ResourceDC>(AllResources) : new List<ResourceDC>();

			Scheduler.ActiveView.LayoutChanged();
		}

		private void RessourcenTV_OnClick(object sender, RoutedEventArgs e)
		{
			var cb = (CheckBox) sender;
			var selectedResource = cb.DataContext as ResourceDC;

			if (CheckBoxConverter != null && selectedResource != null)
				CheckBoxConverter.AktuelleRessource = selectedResource;
		}

		private void AlleKlientennCB_OnClick(object sender, RoutedEventArgs e)
		{
			var cb = (CheckBox) sender;
			if (!cb.IsChecked.HasValue) return;

			if (NurMeineKlientenCB.IsChecked.HasValue && NurMeineKlientenCB.IsChecked.Value)
				SelectedCustomers = cb.IsChecked.Value ? new List<CompactCustomerDC>(GefilterteKlienten) : new List<CompactCustomerDC>();
			else
				SelectedCustomers = cb.IsChecked.Value ? new List<CompactCustomerDC>(AllCustomers) : new List<CompactCustomerDC>();

			Scheduler.ActiveView.LayoutChanged();
		}

		private void KlientenListe_OnClick(object sender, RoutedEventArgs e)
		{
			var cb = (CheckBox) sender;
			var selectedCustomer = cb.DataContext as CompactCustomerDC;

			if (CheckBoxConverter != null && selectedCustomer != null)
				CheckBoxConverter.AktuellerKlient = selectedCustomer;
		}

		private void ListItemCheckedEvent(object sender, RoutedEventArgs e)
		{
			Scheduler.ActiveView.LayoutChanged();
		}

		private void btnRemoveElement_Click(object sender, RoutedEventArgs e)
		{
			var selectedDC = ((Button) sender).Tag as IDataContract;

			if ((selectedDC as CompactEmployeeDC) != null)
			{
				var employee = selectedDC as CompactEmployeeDC;
				SelectedEmployees.Remove(employee);
				OnPropertyChanged("SelectedEmployees");

			    if (employee.Equals(BeWoApp.CompactLoggedOnEmployee))
			    {
			        ZeigeNurMeineTermine = false;
			    }
                else if (SelectedEmployees.Count == 1 && SelectedEmployees.First().Equals(BeWoApp.CompactLoggedOnEmployee))
                {
                    ZeigeNurMeineTermine = true;
                }
			}
			else if ((selectedDC as CompactCustomerDC) != null)
			{
				var customer = selectedDC as CompactCustomerDC;
				SelectedCustomers.Remove(customer);
				OnPropertyChanged("SelectedCustomers");
			}
			else if ((selectedDC as ResourceDC) != null)
			{
				var resource = selectedDC as ResourceDC;
				SelectedResources.Remove(resource);
				OnPropertyChanged("SelectedResources");
			}
			
			OnPropertyChanged("SelectedItems");
			Scheduler.ActiveView.LayoutChanged();
		}

		private void ButtonDayView_Click(object sender, RoutedEventArgs e)
		{
			Scheduler.ActiveViewType = SchedulerViewType.Day;
			currentViewType = Scheduler.ActiveViewType;
			UpdateOptionPanel();

			DayViewOptions.Visibility = Visibility.Visible;
			TimelineViewOptions.Visibility = Visibility.Collapsed;
		}

		private void ButtonMonthView_Click(object sender, RoutedEventArgs e)
		{
			Scheduler.ActiveViewType = SchedulerViewType.Month;
			currentViewType = Scheduler.ActiveViewType;
			var interval = Scheduler.ActiveView.GetVisibleIntervals();
			Scheduler.ActiveView.SetVisibleIntervals(new TimeIntervalCollection {new TimeInterval(interval.Start, new TimeSpan(35, 0, 0, 0))});

			UpdateOptionPanel();
		}

		private void ButtonWorkWeekView_Click(object sender, RoutedEventArgs e)
		{
			Scheduler.ActiveViewType = SchedulerViewType.WorkWeek;
			currentViewType = Scheduler.ActiveViewType;
			UpdateOptionPanel();
		}

		private void ButtonWeekView_Click(object sender, RoutedEventArgs e)
		{
			Scheduler.ActiveViewType = SchedulerViewType.Week;
			currentViewType = Scheduler.ActiveViewType;
			UpdateOptionPanel();
		}

		private void ButtonTimelineView_Click(object sender, RoutedEventArgs e)
		{
			Scheduler.ActiveViewType = SchedulerViewType.Timeline;
			currentViewType = Scheduler.ActiveViewType;
			UpdateOptionPanel();

			DayViewOptions.Visibility = Visibility.Collapsed;
			TimelineViewOptions.Visibility = Visibility.Visible;
		}

		private void SpinEditDayViewDayCount_EditValueChanged(object sender, EditValueChangedEventArgs e)
		{
			int count;
			if (e.NewValue != null && Int32.TryParse(e.NewValue.ToString(), out count) && count > 0)
			{
				Scheduler.DayView.DayCount = count;
				timelineDayCount = count;
			}
		}

		private void SpinEditTimelineViewDayCount_EditValueChanged(object sender, EditValueChangedEventArgs e)
		{
			int count;
			if (e.NewValue == null || !Int32.TryParse(e.NewValue.ToString(), out count)) return;

			if (count > 0)
			{
				Scheduler.TimelineView.IntervalCount = count;
				timelineDayCount = count;
			}
		}
		#endregion

		private bool enabled;
		public bool Enabled 
		{
			get { return enabled; }
			set 
			{
				enabled = value;
				OnPropertyChanged("Enabled");
			} 
		}
		private void UpdateRequestString()
		{
			ServiceFacade.DoResourceServiceSync(r => Liste = r.GetAllOpenAppointmentsForEmployee(BeWoApp.LoggedOnEmployee.EmployeeOid.Value));
			var summe = Liste.Count;

			Enabled = Liste.Count > 0;
			Requests = string.Format("{0} Benachrichtigung{1}", summe == 0 ? "keine" : summe.ToString(), summe == 1 ? "" : "en");
		}

		private List<SchedulerAppointmentDC> Liste = new List<SchedulerAppointmentDC>(); 

		private void NewSchedulerStorage_AppointmentsChanged(object sender, PersistentObjectsEventArgs e)
		{
			if (IgnoreChangeEvents)
			{
			    return;
			}

			var appList = e.Objects.Cast<Appointment>().ToList();

			if (appList.Any(f => f.CustomFields["IsPrivate"] != null && (bool)f.CustomFields["IsPrivate"]))
			{
			    ShowPrivateAppointmentsCheckBox.IsChecked = true;
			}

			ViewModel.ActiveAppointmentViewModel.SaveAppointments(Scheduler, appList);
			
			UpdateVM(true);
		}

		private void NewSchedulerControl_FilterAppointments(object sender, PersistentObjectCancelEventArgs e)
		{
			if (IgnoreChangeEvents)
			{
			    return;
			}
			
			var showOnlyPrivateApps = ShowPrivateAppointmentsCheckBox.IsChecked.HasValue && ShowPrivateAppointmentsCheckBox.IsChecked.Value;

			if (showOnlyPrivateApps)
			{
			    e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment("NurPrivate", null, ((Appointment) e.Object), true);
			}

			var me = MitarbeiterEbenenCheckBox.IsChecked.HasValue && MitarbeiterEbenenCheckBox.IsChecked.Value;
			var ke = KlientenEbenenCheckBox.IsChecked.HasValue && KlientenEbenenCheckBox.IsChecked.Value;
			var re = RessourcenEbenenCheckBox.IsChecked.HasValue && RessourcenEbenenCheckBox.IsChecked.Value;

			if ((me || ke || re) && !SelectedItems.Any())
			{
				e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment("Ebenen", new List<bool> { me, re, ke }, ((Appointment)e.Object), showOnlyPrivateApps);
				return;
			}

			var m = CheckBoxConverter.SelektierteMitarbeiter;
			var r = CheckBoxConverter.SelektierteRessourcen;
			var k = CheckBoxConverter.SelektierteKlienten;
		    ;
            if ((m.Any() || r.Any() || k.Any()) && ZeigeNurMeineTermineCheckBox.IsChecked == false)
			{
				e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment("NachAuswahl", new Dictionary<string, object> { { "Mitarbeiter", m }, { "Ressourcen", r }, { "Klienten", k } }, ((Appointment)e.Object), showOnlyPrivateApps);
				return;
			}

		    var abc = ((Appointment) e.Object).Subject;
		    if (abc.Equals("Ohne Chandler"))
		    {
		        
		    }


		    e.Cancel = ViewModel.ActiveAppointmentViewModel.FilterAppointment("NurEigene", new Dictionary<string, object> { { "Mitarbeiter", m }, { "Ressourcen", r }, { "Klienten", k }, {"Teams", EmployeesTeams} }, ((Appointment)e.Object), showOnlyPrivateApps);
		}

		private void NewSchedulerStorage_AppointmentDeleting(object sender, PersistentObjectCancelEventArgs e)
		{
			var app = e.Object as Appointment;

			if (app != null && app.Type != AppointmentType.ChangedOccurrence)
			{
				var msg = string.Format("Möchten Sie den gewählten Termin wirklich löschen?");

				if (app.Type != AppointmentType.DeletedOccurrence && MessageBox.Show(msg, "BeWoPlaner", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
				{
					e.Cancel = true;
				}
				else
				{
					var appList = new List<Appointment>();

					if (app.Type != AppointmentType.ChangedOccurrence)
					{
					    appList.Add(app);
					}

					ViewModel.ActiveAppointmentViewModel.DeleteAppointments(Scheduler, appList);
				}
			}

			UpdateRequestString();
			UpdateVM(true);
		}

		private void NewSchedulerStorage_AppointmentsInserted(object sender, PersistentObjectsEventArgs e)
		{
			var appList = e.Objects.Cast<Appointment>().ToList();

			if(appList.Any(f => f.CustomFields["IsPrivate"] != null && (bool) f.CustomFields["IsPrivate"]))
			{
			    ShowPrivateAppointmentsCheckBox.IsChecked = true;
			}

			ViewModel.ActiveAppointmentViewModel.InsertAppointments(Scheduler, appList);
			UpdateRequestString();
			UpdateVM(true);

			//Synchronize();
		}

		private void scheduler_EditAppointmentFormShowing(object sender, EditAppointmentFormEventArgs e)
		{
			var control = (DevExpress.Xpf.Scheduler.SchedulerControl) sender;
			
			if (istNeu)
			{
				var n = SelectedEmployees.Select(item => new Employee2SchedulerAppointmentDC {Employee = item, ParticipationAnswer = ParticipationAnswer.Offen}).ToList();
				e.Appointment.CustomFields["EmployeeList"] = n;
				e.Appointment.CustomFields["CustomerList"] = new List<CompactCustomerDC>(SelectedCustomers);
				e.Appointment.CustomFields["ResourceList"] = new List<ResourceDC>(SelectedResources);
			}

			var form = ViewModel.GetEditAppointmentForm(control, e.Appointment);
			if (form == null)
			{
			    return;
			}

			e.Form = form;
			e.AllowResize = false;
			
			if (istNeu)
			{
			    istNeu = false;
			}
		}

		private void SchedulerControl_EditRecurrentAppointmentFormShowing(object sender, EditAppointmentFormEventArgs e) { }

		private void scheduler_PopupMenuShowing(object sender, SchedulerMenuEventArgs e)
		{
			var ZusageUntermenue = e.Menu.ItemLinks.FirstOrDefault(f=>f.GetType() == typeof(BarSubItemLink) && ((BarSubItemLink) f).Item.Name.Equals("TeilnahmeMenue"));

            if (ZusageUntermenue == null || ((List<Employee2SchedulerAppointmentDC>)Scheduler.SelectedAppointments[0].CustomFields["EmployeeList"]).Any(a => a.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid)))
            {
                return;
            }

			e.Menu.ItemLinks.Remove(ZusageUntermenue);
		}

		private bool istNeu;
		private void scheduler_InitNewAppointment(object sender, AppointmentEventArgs e)
		{
			istNeu = true;
			ViewModel.InitNewAppointment(e.Appointment);
		}

		private void scheduler_AppointmentViewInfoCustomizing(object sender, DevExpress.Xpf.Scheduler.AppointmentViewInfoCustomizingEventArgs e)
		{
			e.ViewInfo.CustomViewInfo = e.ViewInfo.Appointment.CustomFields;
		}

		private void AllowAppointmentAenderung(object sender, AppointmentOperationEventArgs e)
		{
			var darfTerminDetailsSehen = true;
			var appointment            = e.Appointment;
			var originator             = (CompactEmployeeDC) appointment.CustomFields["Originator"];
			var mitarbeiterliste       = (List<Employee2SchedulerAppointmentDC>)appointment.CustomFields["EmployeeList"];

            var hatMitarbeiter  = mitarbeiterliste.Count > 0 && !(mitarbeiterliste.Count == 1 && mitarbeiterliste.ElementAt(0).Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid));
			var hatKlienten     = ((List<CompactCustomerDC>) appointment.CustomFields["CustomerList"]).Count > 0;
			//var hatRessourcen = ((List<ResourceDC>) apt.CustomFields["ResourceList"]).Count > 0;

			if (hatMitarbeiter)
			{
			    darfTerminDetailsSehen = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAendern);
			}

			if (hatKlienten)
			{
			    darfTerminDetailsSehen = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderKliententermineAendern);
			}

            //if (hatRessourcen)
            //{
            //    darfTerminDetailsSehen = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAendern);
            //}

			//if (hatRessourcen && !o.Equals(BeWoApp.LoggedOnEmployeeCompact)) 
            //{
            //    darfTerminDetailsSehen = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderRessourcentermineAndererAendern);
            //}

            if (darfTerminDetailsSehen == false)
			{
			    darfTerminDetailsSehen = mitarbeiterliste.Select(ml => ml.Employee).Any(a => a.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid)) || originator.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid);
			}

            if (!originator.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) && (bool)appointment.CustomFields["IsPrivate"] && !mitarbeiterliste.Any(em => em.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid)))
            {
                darfTerminDetailsSehen = false;
            }

			e.Allow = darfTerminDetailsSehen;
		}

		private void AllowAppointmentCreateEvent(object sender, AppointmentOperationEventArgs e)
		{
			var darfAnlegen = BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderKliententermineAnlegen) ||
							  BeWoApp.LoggedOnUser.HasRight(UserRightType.KalenderMitarbeitertermineAnlegen);

			e.Allow = darfAnlegen;
		}

		private void UpdateOptionPanel()
		{
			switch (ViewTypeConvert.ToAppointmentViewType(currentViewType))
			{
				case AppointmentViewType.Day:
					TimelineViewOptions.Visibility     = Visibility.Collapsed;
					DayViewOptions.Visibility          = Visibility.Visible;
					SpinEditDayViewDayCount.Value      = Scheduler.DayView.DayCount;
					timelineDayCount                   = 0;
					break;
				case AppointmentViewType.Timeline:
					TimelineViewOptions.Visibility     = Visibility.Visible;
					DayViewOptions.Visibility          = Visibility.Collapsed;
					SpinEditTimelineViewDayCount.Value = timelineDayCount == 0 ? Scheduler.TimelineView.IntervalCount : timelineDayCount;
					break;
				default:
					timelineDayCount                   = 0;
					TimelineViewOptions.Visibility     = Visibility.Collapsed;
					DayViewOptions.Visibility          = Visibility.Collapsed;
					break;
			}

			Scheduler.WeekView.AppointmentDisplayOptions.AppointmentAutoHeight = true;
			Scheduler.MonthView.AppointmentDisplayOptions.AppointmentAutoHeight = true;
			Scheduler.TimelineView.AppointmentDisplayOptions.AppointmentAutoHeight = true;
		}

		private void ShowPrivateAppointmentsCheckBox_OnClick(object sender, RoutedEventArgs e)
		{
			Scheduler.ActiveView.LayoutChanged();
		}

		private void LeftExpanderClick(object sender, RoutedEventArgs e)
		{
			if (!LeftExpanderButton.IsChecked.HasValue)
			{
			    return;
			}

            AuswahlGrid.Visibility = ZeigeNurMeineTermineCheckBox.Visibility = LeftExpanderButton.IsChecked.Value ? Visibility.Collapsed : Visibility.Visible;
		}

		private void RightExpanderClick(object sender, RoutedEventArgs e)
		{
			if (!RightExpanderButton.IsChecked.HasValue)
			{
			    return;
			}

			DateNavigator.Visibility = RightExpanderButton.IsChecked.Value ? Visibility.Collapsed : Visibility.Visible;
		}

		private void NurEigeneKlientenAnzeigen(object sender, RoutedEventArgs e)
		{
            //!BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View) && BeWoApp.LoggedOnUser.HasRight(UserRightType.Customer_ViewMyCustomers) ? AllCustomers : 

		    var relatedCustomerOids = BeWoApp.LoggedOnEmployee.RelatedCustomers.Select(s => s.Customer.CustomerOid);

			if (NurMeineKlientenCB.IsChecked.HasValue && NurMeineKlientenCB.IsChecked.Value)
			{
                GefilterteKlienten = AllCustomers.Where(ac => relatedCustomerOids.Contains(ac.CustomerOid)).ToList();
			}
			else if (NurMeineKlientenCB.IsChecked.HasValue && !NurMeineKlientenCB.IsChecked.Value)
			{
			    GefilterteKlienten = AllCustomers;
			}
		}

		private void TextBoxEmployees_OnTextChanged(object sender, TextChangedEventArgs e)
		{
			var suchtext = ((TextBox)sender).Text;
			
			GefilterteMitarbeiter = AllEmployees.Where(m => m.FirstName.ToLower().Contains(suchtext.ToLower()) ||
															m.LastName.ToLower().Contains(suchtext.ToLower())).ToList();
		}

		private void TextBoxCustomers_OnTextChanged(object sender, TextChangedEventArgs e)
		{
			var suchtext = ((TextBox)sender).Text;

			GefilterteKlienten = AllCustomers.Where(m => m.FullName.ToLower().Contains(suchtext.ToLower())).ToList();
		}

		private void FensterOeffnen()
		{
			var neueListe = new SchedulerAppointmentListVM(Liste, AllCustomers, AllEmployees, Category2ResourcesDictionary);

			var vm = neueListe;

			var zuBestaetigen = vm.Appointments.Where(app =>
			{
				if (!app.CustomFields.ContainsKey("EmployeeList"))
				{
				    return false;
				}

				var empList = (List<Employee2SchedulerAppointmentDC>) app.CustomFields["EmployeeList"];

                return empList.Any(a => a.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) && a.ParticipationAnswer == ParticipationAnswer.Offen);
			}).ToList();

			var updates = vm.Appointments.Where(app =>
			{
				if (!app.CustomFields.ContainsKey("Originator") || !app.CustomFields.ContainsKey("EmployeeList"))
				{
				    return false;
				}

				var empList = (List<Employee2SchedulerAppointmentDC>) app.CustomFields["EmployeeList"];
				var or = (CompactEmployeeDC) app.CustomFields["Originator"];

                return or.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) && empList.Any(a => a.IsPChanged && a.ParticipationAnswer != ParticipationAnswer.Offen && !a.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid));
			}).ToList();

			if (!zuBestaetigen.Any() && !updates.Any())
			{
			    return;
			}

			var x = new RequestAnswerView(zuBestaetigen, updates);

			x.Closed += RequestAnswerViewClosedEvent;
			x.ParticipationChanged += UpdateRequestStringEvent;
			x.ParticipationChanged += UpdateBeiParticipationChanged;
			
			x.Show();
		}

		private void RequestAnswerViewClosedEvent(object sender, EventArgs e)
		{
			UpdateVM(true);
			UpdateRequestString();
		}

		private void ShowAppointmentRequests(object sender, RequestNavigateEventArgs e)
		{
			FensterOeffnen();
		}

		private void UpdateBeiParticipationChanged(object sender, EventArgs e)
		{
			UpdateVM();
		}

		private void UpdateRequestStringEvent(object sender, EventArgs e)
		{
			UpdateRequestString();
		}

		private void AuswahlAufhebenClick(object sender, RoutedEventArgs e)
		{
			SelectedResources.Clear();
			SelectedEmployees.Clear();
			SelectedCustomers.Clear();

			AlleMitarbeiterCB.IsChecked = false;
			AlleKlientenCB.IsChecked    = false;
			AlleRessourcenCB.IsChecked  = false;

			OnPropertyChanged("SelectedCustomers");
			OnPropertyChanged("SelectedEmployees");
			OnPropertyChanged("SelectedResources");
			OnPropertyChanged("SelectedItems");
		}

		private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var tabControl = (TabControl)sender;
			var selectedItem = (TabItem)tabControl.SelectedItem;

			var mitarbeiterPinsel = new LinearGradientBrush(new GradientStopCollection { new GradientStop(Color.FromRgb(69, 153, 59), 0), new GradientStop(Color.FromRgb(32, 92, 25), 1) }, new Point(0.5, 0), new Point(0.5, 1));
			var klientenPinsel = new LinearGradientBrush(new GradientStopCollection { new GradientStop(Color.FromRgb(59, 119, 153), 0), new GradientStop(Color.FromRgb(25, 72, 92), 1) }, new Point(0.5, 0), new Point(0.5, 1));
			var ressourcenPinsel = new LinearGradientBrush(new GradientStopCollection { new GradientStop(Color.FromRgb(4, 180, 208), 0), new GradientStop(Color.FromRgb(3, 129, 149), 1) }, new Point(0.5, 0), new Point(0.5, 1));

			switch (selectedItem.Header.ToString())
			{
				case "Mitarbeiter":
					tabControl.Background = mitarbeiterPinsel;
					tabControl.BorderBrush = mitarbeiterPinsel;
					break;
				case "Klienten":
					tabControl.Background = klientenPinsel;
					tabControl.BorderBrush = klientenPinsel;
					break;
				case "Ressourcen":
					tabControl.Background = ressourcenPinsel;
					tabControl.BorderBrush = ressourcenPinsel;
					break;
			}
		}

		private void ReloadButton_OnClick(object sender, RoutedEventArgs e)
		{
			UpdateVM(true);
		}

		private void ZusagenButtonItem_OnItemClick(object sender, ItemClickEventArgs e)
		{
			if (Scheduler.SelectedAppointments.Count <= 0)
			{
			    return;
			}

			ZusageAendern(ParticipationAnswer.Zusage, Scheduler.SelectedAppointments[0]);
		}

		private void MitVorbehaltButtonItem_OnItemClick(object sender, ItemClickEventArgs e)
		{
			if (Scheduler.SelectedAppointments.Count <= 0)
			{
			    return;
			}

			ZusageAendern(ParticipationAnswer.Vorbehalt, Scheduler.SelectedAppointments[0]);
		}

		private void AbsagenButtonItem_OnItemClick(object sender, ItemClickEventArgs e)
		{
			if (Scheduler.SelectedAppointments.Count <= 0)
			{
			    return;
			}

			ZusageAendern(ParticipationAnswer.Absage, Scheduler.SelectedAppointments[0]);
		}

		private void ZusageAendern(ParticipationAnswer antwort, Appointment sa)
		{
			var el = (List<Employee2SchedulerAppointmentDC>) sa.CustomFields["EmployeeList"];
			var neu = el.DoForEach(dfe =>
			{
                if (!dfe.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid))
                {
                    return;
                }

				dfe.ParticipationAnswer = antwort;
				dfe.IsPC_CheckedTs = null;
			}).ToList();
			sa.CustomFields["EmployeeList"] = neu;

			UpdateVM(true);
		}

		private void MeinTB_OnChecked(object sender, RoutedEventArgs e)
		{
			var tb = (ToggleButton) sender;

			if (tb == null || tb.IsChecked == null)
			{
			    return;
			}

			if (!tb.IsChecked.Value)
			{
				MitarbeiterSuchGrid.Visibility = Visibility.Collapsed;
				MitarbeiterSuchTextBox.Clear();
			}
			else
			{
				MitarbeiterSuchGrid.Visibility = Visibility.Visible;
				MitarbeiterSuchTextBox.Focus();
			}
		}

		private void MeinTB2_OnChecked(object sender, RoutedEventArgs e)
		{
			var tb = (ToggleButton)sender;

			if (tb == null || tb.IsChecked == null)
			{
			    return;
			}

			if (!tb.IsChecked.Value)
			{
				KlientenSuchGrid.Visibility = Visibility.Collapsed;
				KlientenSuchTextBox.Clear();
			}
			else
			{
				KlientenSuchGrid.Visibility = Visibility.Visible;
				KlientenSuchTextBox.Focus();
			}
		}

		private void SchedulerStorage_OnFetchAppointments(object sender, FetchAppointmentsEventArgs e)
		{
			UpdateVM();
		}

		private void UpdateVM(bool realoadBtnPressed = false)
		{
			if (ViewModel == null)
			{
				return;
			}

			var range = Scheduler.ActiveView.GetVisibleIntervals();
			var start = range.Start;
			var end   = range.End;

			if (start > lastFetchedInterval.Start && end < lastFetchedInterval.End && !realoadBtnPressed)
			{
				return;
			}

			lastFetchedInterval = new TimeInterval(start - FetchPadding, end + FetchPadding);
			
			ViewModel.UpdateAppointmentViewModel(start, end);

		    GefilterteMitarbeiter = ViewModel.ActiveAppointmentViewModel.AllEmployees;
		    AllEmployees          = ViewModel.ActiveAppointmentViewModel.AllEmployees;
		    GefilterteKlienten    = ViewModel.ActiveAppointmentViewModel.AllCustomers;
		    AllCustomers          = ViewModel.ActiveAppointmentViewModel.AllCustomers;

		    Category2ResourcesDictionary = ViewModel.ActiveAppointmentViewModel.Categories2Resources;

		    SelectedEmployees = AllEmployees.Where(w => SelectedEmployees.Any(a => a.EmployeeOid.Equals(w.EmployeeOid))).ToList();
		    SelectedCustomers = AllCustomers.Where(w => SelectedCustomers.Any(a => a.CustomerOid.Equals(w.CustomerOid))).ToList();
		    SelectedResources = AllResources.Where(w => SelectedResources.Any(a => a.ResourceOid.Equals(w.ResourceOid))).ToList();

		    var items = SelectedItems;

            OnPropertyChanged("AllResources");
            OnPropertyChanged("SelectedEmployees");
            OnPropertyChanged("SelectedItems");
		}

		//private void ExportAsiCal(object sender, RoutedEventArgs e)
		//{
		//	var dialog = new SaveFileDialog {Filter = "iCalendar files (*.ics)|*.ics", FilterIndex = 1};

		//	if (dialog.ShowDialog() != true) 
		//		return;
			
		//	using (var stream = dialog.OpenFile())
		//	{
		//		ExportAppointmentsAs_iCal(stream);
		//	}
		//}

		//void ExportAppointmentsAs_iCal(Stream stream)
		//{
		//	if (stream == null)
		//		return;
		//	try
		//	{
		//		var productIdentifier = string.Format("-//{0}//DXScheduler iCalendarExchange Example//DE", BeWoApp.Mandator);
		//		var exporter = new iCalendarExporter(Scheduler.GetCoreStorage()) { ProductIdentifier = productIdentifier }; 
				
		//		//exporter.AppointmentExporting += OnAppointmentExporting;
		//		exporter.Export(stream);
		//	}
		//	catch (Exception e)
		//	{
		//		MessageBox.Show(string.Format("Der Kalender konnte leider nicht exportiert werden.\n{0}", e.Message), "Fehler beim Export", MessageBoxButton.OK, MessageBoxImage.Error);
		//	}
		//}

		//private void OnAppointmentExporting(object sender, AppointmentExportingEventArgs appointmentExportingEventArgs)
		//{
		//	var iCalArgs = (iCalendarAppointmentExportingEventArgs) appointmentExportingEventArgs;
		//	var vEvent = iCalArgs.VEvent;

		//	var ma = (List<Employee2SchedulerAppointmentDC>)appointmentExportingEventArgs.Appointment.CustomFields["EmployeeList"];
		//	var ca = (List<CompactCustomerDC>)appointmentExportingEventArgs.Appointment.CustomFields["CustomerList"];
		//	var ra = (List<ResourceDC>)appointmentExportingEventArgs.Appointment.CustomFields["ResourceList"];
		//}

		//private void SyncWithOutlook(object sender, RoutedEventArgs e)
		//{
		//	Synchronize();
		//}

		private void PrintCalendar(object sender, RequestNavigateEventArgs e)
		{
			if (Scheduler.ActiveView.GetAppointments().Count == 0)
			{
				MessageBox.Show("Das Drucken ist nicht möglich, da im ausgewählten Intervall keine Termine vorhanden sind.",
								"Drucken nicht möglich",
								MessageBoxButton.OK,
								MessageBoxImage.Error);
				return;
			}
			
			var range = Scheduler.ActiveView.GetVisibleIntervals();
			var datesList = new List<DateTime>();

            if (range.GetType() == typeof(WeekIntervalCollection))
		    {
		        for (var i = 0; i < range.Duration.Days; i++)
		        {
					datesList.Add(range.Start.AddDays(i));
		        }
		    }
		    else
		    {
			    datesList.AddRange(range.Select(x => x.Start));
		    }
			
			var apps                  = Scheduler.ActiveView.GetAppointments().ToList();
			var appointmentOidListe   = apps.Where(w => (!w.IsOccurrence && !w.IsRecurring) || w.IsException).Select(app => Convert.ToInt64(((SchedulerAppointmentVM) app.GetSourceObject(Scheduler.GetCoreStorage())).Id)).Distinct().ToList();
			var serienTerminOids      = apps.Where(w => w.IsRecurring || w.IsOccurrence).Select(app => Convert.ToInt64(((SchedulerAppointmentVM)app.RecurrencePattern.GetSourceObject(Scheduler.GetCoreStorage())).Id)).Distinct().ToList();
			var serienTermine         = new List<SchedulerAppointmentDC>();
			var recurringAppointments = new List<Appointment>();

			foreach (var app in apps.Where(w => w.IsOccurrence || w.IsRecurring).Where(app => !recurringAppointments.Any(a => a.RecurrenceInfo.Id.Equals(app.RecurrenceInfo.Id))))
			{
				recurringAppointments.Add(app);
			}
			
			foreach (var serienTermin in recurringAppointments)
			{
				var basistermin             = (SchedulerAppointmentVM) serienTermin.RecurrencePattern.GetSourceObject(Scheduler.GetCoreStorage());
				var info                    = serienTermin.RecurrenceInfo;
				var ausnahmen               = apps.Where(w => w.RecurrenceInfo != null && w.RecurrenceInfo.Id.Equals(info.Id) && w.IsException).ToList();
				var calc                    = OccurrenceCalculator.CreateInstance(info);
				var ttc                     = new TimeInterval(range.Start, range.End + new TimeSpan(1, 0, 0));
				var kollektionOhneAusnahmen = calc.CalcOccurrences(ttc, serienTermin.RecurrencePattern).Where(w => (w.RecurrenceIndex != 0 && !w.IsException)).ToList();

				if (ausnahmen.Any(appointment => appointment.IsException && appointment.RecurrenceIndex == 0) && basistermin.DataContract.SchedulerAppointmentOid != null)
				{
					serienTerminOids.Remove(basistermin.DataContract.SchedulerAppointmentOid.Value);
				}

				if (ausnahmen.Count > 0)
				{
				    kollektionOhneAusnahmen = kollektionOhneAusnahmen.Where(w => !ausnahmen.Select(s => s.RecurrenceIndex).Contains(w.RecurrenceIndex)).ToList();
				}

				serienTermine.AddRange(kollektionOhneAusnahmen.Select(z => new SchedulerAppointmentDC
				{
					AllDay = z.AllDay, CustomerList = basistermin.CustomerList, EmployeeList = basistermin.EmployeeList, ResourceList = basistermin.ResourceList, StartDate = z.Start, EndDate = z.End, Description = z.Description, IsPrivate = basistermin.IsPrivate, Location = z.Location, Subject = z.Subject, LabelId = z.LabelId, Type = (int) z.Type, Originator = basistermin.Originator, RecurrenceInfo = z.RecurrenceInfo.ToXml()
				}));
			}
			
			appointmentOidListe.AddRange(serienTerminOids.Where(w => !appointmentOidListe.Contains(w)));


			var mehrTaegigeTermine = apps.Where(a => !a.SameDay && !(!a.SameDay && a.AllDay && a.Duration == new TimeSpan(1,0,0,0))).Select(s => ((SchedulerAppointmentVM)s.GetSourceObject(Scheduler.GetCoreStorage())).CommitToDataContract()).ToList();
			appointmentOidListe.RemoveRange(mehrTaegigeTermine.Select(s => s.SchedulerAppointmentOid.Value));
			var neueTermine = new List<SchedulerAppointmentDC>();

			foreach (var termin in mehrTaegigeTermine)
			{
				var tage = termin.StartDate.Value.GetDayNumberBetweenTwoDates(termin.EndDate.Value);

				if (termin.AllDay)
				{
					tage -= 1;
				}

				if (tage > 0)
				{
					if (termin.AllDay)
					{
						for (var i = 0; i <= tage; i++)
						{
							neueTermine.Add(new SchedulerAppointmentDC
							{
								AllDay                   = termin.AllDay,
								CustomerList             = termin.CustomerList,
							    Description              = termin.Description,
								EmployeeList             = termin.EmployeeList,
								EndDate                  = new DateTime(termin.StartDate.Value.AddDays(i + 1).Year, termin.StartDate.Value.AddDays(i + 1).Month, termin.StartDate.Value.AddDays(i + 1).Day),
								FormerBookingSequenceOid = termin.FormerBookingSequenceOid,
								IsPrivate                = termin.IsPrivate,
								LabelId                  = termin.LabelId,
								Location                 = termin.Location,
								Originator               = termin.Originator,
								RecurrenceInfo           = termin.RecurrenceInfo,
								ReminderInfo             = termin.ReminderInfo,
								ResourceList             = termin.ResourceList,
								StartDate                = new DateTime(termin.StartDate.Value.AddDays(i).Year, termin.StartDate.Value.AddDays(i).Month, termin.StartDate.Value.AddDays(i).Day),
								Status                   = termin.Status,
								Subject                  = termin.Subject,
								Type                     = termin.Type
							});
						}
					}
					else
					{
						for (var i = 0; i <= tage; i++)
						{
							if (i == 0)
							{
								neueTermine.Add(new SchedulerAppointmentDC
								{
									AllDay                   = false,
									CustomerList             = termin.CustomerList,
									Description              = termin.Description,
									EmployeeList             = termin.EmployeeList,
									EndDate                  = new DateTime(termin.StartDate.Value.AddDays(1).Year, termin.StartDate.Value.AddDays(1).Month, termin.StartDate.Value.AddDays(1).Day),
									FormerBookingSequenceOid = termin.FormerBookingSequenceOid,
									IsPrivate                = termin.IsPrivate,
									LabelId                  = termin.LabelId,
									Location                 = termin.Location,
									Originator               = termin.Originator,
									RecurrenceInfo           = termin.RecurrenceInfo,
									ReminderInfo             = termin.ReminderInfo,
									ResourceList             = termin.ResourceList,
									StartDate                = termin.StartDate,
									Status                   = termin.Status,
									Subject                  = termin.Subject,
									Type                     = termin.Type
								});
							}
							else if (i == tage)
							{
								neueTermine.Add(new SchedulerAppointmentDC
								{
									AllDay                   = false,
									CustomerList             = termin.CustomerList,
									Description              = termin.Description,
									EmployeeList             = termin.EmployeeList,
									EndDate                  = termin.EndDate,
									FormerBookingSequenceOid = termin.FormerBookingSequenceOid,
									IsPrivate                = termin.IsPrivate,
									LabelId                  = termin.LabelId,
									Location                 = termin.Location,
									Originator               = termin.Originator,
									RecurrenceInfo           = termin.RecurrenceInfo,
									ReminderInfo             = termin.ReminderInfo,
									ResourceList             = termin.ResourceList,
									StartDate                = new DateTime(termin.EndDate.Value.Year, termin.EndDate.Value.Month, termin.EndDate.Value.Day),
									Status                   = termin.Status,
									Subject                  = termin.Subject,
									Type                     = termin.Type
								});
							}
							else
							{
								neueTermine.Add(new SchedulerAppointmentDC
								{
									AllDay                   = true,
									CustomerList             = termin.CustomerList,
									Description              = termin.Description,
									EmployeeList             = termin.EmployeeList,
									EndDate                  = new DateTime(termin.StartDate.Value.AddDays(i + 1).Year, termin.StartDate.Value.AddDays(i + 1).Month, termin.StartDate.Value.AddDays(i + 1).Day),
									FormerBookingSequenceOid = termin.FormerBookingSequenceOid,
									IsPrivate                = termin.IsPrivate,
									LabelId                  = termin.LabelId,
									Location                 = termin.Location,
									Originator               = termin.Originator,
									RecurrenceInfo           = termin.RecurrenceInfo,
									ReminderInfo             = termin.ReminderInfo,
									ResourceList             = termin.ResourceList,
									StartDate                = new DateTime(termin.StartDate.Value.AddDays(i).Year, termin.StartDate.Value.AddDays(i).Month, termin.StartDate.Value.AddDays(i).Day),
									Status                   = termin.Status,
									Subject                  = termin.Subject,
									Type                     = termin.Type
								});
							}
						}
					}
				}
			}

			var variablenDictionary = new Dictionary<String, Object>
			{
				{ "appointmentOidListe", appointmentOidListe },
				{ "datesList",           datesList },
				{ "employeeOid",         BeWoApp.LoggedOnEmployee.EmployeeOid },
				{ "serienTermine",       serienTermine },
				{"mehrtaegigeTermine",   neueTermine}
			};

			BeWoUtils.ShowReport("Kalender", null, variablenDictionary, ReportEnum.KalenderMonatsReportEnum);
		}

		public void PreselectCustomer(long pCustomerOid)
		{
			if (AllCustomers.Any(c => c.CustomerOid.Equals(pCustomerOid)))
			{
				SelectedCustomers = new List<CompactCustomerDC> {AllCustomers.Find(f => f.CustomerOid.Equals(pCustomerOid))};
				OnPropertyChanged("SelectedCustomers");
				OnPropertyChanged("SelectedItems");
				OnPropertyChanged("GefilterteKlienten");
			}
		}

		private void DateNavigator_OnSelectedDatesChanged(object sender, EventArgs e)
		{
			currentViewType = Scheduler.ActiveViewType;
		}

		private void MitarbeiterVerfuegbarkeitPruefenButtonItem_OnItemClick(object sender, ItemClickEventArgs e)
		{
			var intervall = Scheduler.ActiveView.SelectedInterval;

			ServiceFacade.DoEmployeeServiceAsync(s1 => s1.GetAllActiveEmployeesCompact(),
												dcs => ServiceFacade.DoReportServiceAsync(
													s2 => s2.GetMitarbeiterverfuegbarkeiten(dcs, intervall.Start, intervall.End), s3 => this.Dispatch(() =>
													{
														var mviv = new MitarbeiterverfuegbarkeitsinfoView(s3, intervall.Start, intervall.End);

														if (mviv.CommandBindings.Count == 0)
														{
															mviv.CommandBindings.Add(
																new CommandBinding(
																	ApplicationCommands.Close,
																	(s, e2) =>
																	{
																		if (!mviv.DoSaveCheck())
																			return;

																		popup_content.Visibility = Visibility.Hidden;
																		popup_content.Child      = null;
																	}));
														}

														popup_content.Child = mviv;
														popup_content.Height = 600;
														popup_content.Width = 1000;
														popup_content.Visibility = Visibility.Visible;
													})));
		}

	    private void MitarbeiterfarbenEinAusCheckBox_OnChecked(object sender, RoutedEventArgs e)
	    {
	        var cb = (CheckBox) sender;
	        IsEmployeeBrushVisible = cb.IsChecked ?? true;
	    }

	    private void NurMeineTermineEinAusCheckBox_OnChecked(object sender, RoutedEventArgs e)
	    {
	        var cb = (CheckBox) sender;

            if (CheckBoxConverter != null && BeWoApp.CompactLoggedOnEmployee != null)
	        {
	            if (cb.IsChecked != null && cb.IsChecked.Value)
	            {
                    SelectedEmployees = new List<CompactEmployeeDC>{BeWoApp.CompactLoggedOnEmployee};
                    CheckBoxConverter.AktuellerMitarbeiter = BeWoApp.CompactLoggedOnEmployee;
	            }
	            else if (cb.IsChecked != null && !cb.IsChecked.Value && SelectedEmployees.Count == 1)
	            {
                    SelectedEmployees.Remove(BeWoApp.CompactLoggedOnEmployee);
	                CheckBoxConverter.AktuellerMitarbeiter = null;
	            }

                OnPropertyChanged("SelectedEmployees");
                OnPropertyChanged("SelectedItems");

                Scheduler.ActiveView.LayoutChanged();
	        }
	    }

	    private void Scheduler_OnLoaded(object sender, RoutedEventArgs e)
	    {
	        UpdateViewModelFilter();
	    }

	    private void UpdateViewModelFilter()
	    {
            OnPropertyChanged("SelectedEmployees");
            OnPropertyChanged("SelectedItems");

            Scheduler.ActiveView.LayoutChanged();
	    }
	}

	#region Converter
	public static class ViewTypeConvert
	{
		public static AppointmentViewType ToAppointmentViewType(SchedulerViewType svt)
		{
			switch (svt)
			{
				case SchedulerViewType.Day:
					return AppointmentViewType.Day;
				case SchedulerViewType.Week:
					return AppointmentViewType.Week;
				case SchedulerViewType.Timeline:
					return AppointmentViewType.Timeline;
				case SchedulerViewType.Month:
					return AppointmentViewType.Month;
				default:
					return AppointmentViewType.WorkWeek;
			}
		}
	}

	public class TextFromIDataContractConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if(value is ResourceDC)
			{
			    return (value as ResourceDC).Name;
			}

			if (value is Employee2SchedulerAppointmentDC)
			{
			    return ((Employee2SchedulerAppointmentDC) value).Employee.SimpleDescription;
			}

			var filterableDC = value as IFilterableDC;
			return filterableDC != null ? filterableDC.SimpleDescription : null;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}

	public class GermanEditorLocalizer : EditorLocalizer
	{
		public override string Language { get { return "Deutsch"; } }

		public override string GetLocalizedString(EditorStringId id)
		{
			return id.Equals(EditorStringId.Today) ? "Heute" : base.GetLocalizedString(id);
		}
	}

	public class ViewInfo2CustomFieldsConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var customFields = (CustomFieldCollection)value;
			var ressourcen = (List<ResourceDC>) customFields["ResourceList"];

			if (parameter != null && parameter.Equals("AlleRessourcen"))
			{
			    return ressourcen;
			}
			
			return null;
		}

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}

	public class CustomField2VisibilityConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var customFields = (CustomFieldCollection)value;
			var mitarbeiter  = (List<Employee2SchedulerAppointmentDC>)customFields["EmployeeList"];
			var ressourcen   = (List<ResourceDC>)customFields["ResourceList"];
			var klienten     = (List<CompactCustomerDC>)customFields["CustomerList"];

			if (parameter == null)
			{
			    return Visibility.Collapsed;
			}

			switch (parameter.ToString())
			{
				case "Ressourcen":
					return ressourcen != null && ressourcen.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
				case "Klienten":
					return klienten != null && klienten.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
				case "Mitarbeiter":
					return mitarbeiter != null && mitarbeiter.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
				case "Trennstrich":
					return mitarbeiter != null && mitarbeiter.Any() || klienten != null && klienten.Any() || ressourcen != null && ressourcen.Any() ? Visibility.Visible : Visibility.Collapsed;
			}

			return Visibility.Collapsed;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}

	public class AppointmentToolTipConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var customfields = (CustomFieldCollection) value;
			var mitarbeiter = (List<Employee2SchedulerAppointmentDC>)customfields["EmployeeList"];
			var ressourcen = (List<ResourceDC>) customfields["ResourceList"];
			var klienten = (List<CompactCustomerDC>) customfields["CustomerList"];
			var tooltip = string.Empty;
			var seperator = "; ";

			if (parameter == null)
			{
			    return tooltip;
			}

			var auswahl = new List<IFilterableDC>();
			switch (parameter.ToString())
			{
				case "Ressourcen":
					seperator = ", ";
					if(ressourcen != null)
					{
					    auswahl = ressourcen.Cast<IFilterableDC>().ToList();
					}
					break;
				case "Mitarbeiter":
					if (mitarbeiter != null)
					{
					    auswahl = mitarbeiter.Select(s => s.Employee).Cast<IFilterableDC>().ToList();
					}
					break;
				case "Klienten":
					if(klienten != null)
					{
					    auswahl = klienten.Cast<IFilterableDC>().ToList();
					}
					break;
			}

			foreach (var item in auswahl)
			{
				var index = auswahl.IndexOf(item);

				if (index%3 == 0 && index < auswahl.Count - 1 && index > 0)
				{
				    tooltip += "\n";
				}

				tooltip += item.ToString();

				if (index < auswahl.Count - 1)
				{
				    tooltip += seperator;
				}
			}

			return tooltip;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}

	public class WidthAdditionMultiConverter : IMultiValueConverter
	{
		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
		{
			var w1 = System.Convert.ToDouble(values[0]);
			var w2 = System.Convert.ToDouble(values[1]);

			return w1 + w2;
		}

		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}

	public class ToolTipTimeViewerConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var vi = (VisualAppointmentViewInfo) value;

			if (parameter == null || vi == null)
			{
			    return string.Empty;
			}

			return parameter.Equals("Start") ? (vi.StartTimeText.Contains("-") ? vi.StartTimeText : vi.StartTimeText + "-") : vi.EndTimeText;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}

	public class FilterBackgroundConverter : IMultiValueConverter
	{
		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
		{
            var farbe = Color.FromRgb(192, 255, 208);
            
			try
			{
				var selectedItems = values[0] as List<IDataContract>;
				if (selectedItems == null || !selectedItems.Any())
				{
				    return new LinearGradientBrush(new GradientStopCollection { new GradientStop(farbe, 1) }, new Point(.5, 0), new Point(.5, 1));
				}

				var customViewInfo = values[1] as CustomFieldCollection;
				if (customViewInfo == null)
				{
				    return new LinearGradientBrush(new GradientStopCollection { new GradientStop(farbe, 1) }, new Point(.5, 0), new Point(.5, 1));
				}

				var aptCustomers = (List<CompactCustomerDC>) customViewInfo["CustomerList"];
				var aptResources = (List<ResourceDC>) customViewInfo["ResourceList"];

				var gradientCollection = new GradientStopCollection();
				var farbKollektion = new List<Color>();

				if (selectedItems.Any(aptCustomers.Contains))
				{
				    farbKollektion.Add(Color.FromRgb(59, 119, 153));
				}

				if (selectedItems.Any(aptResources.Contains))
				{
				    farbKollektion.Add(Color.FromRgb(4, 180, 208));
				}

				switch (farbKollektion.Count)
				{
					case 1:
						var first = aptResources.FirstOrDefault();

				        gradientCollection.Add(first != null ? new GradientStop((Color) (ColorConverter.ConvertFromString(first.Color) ?? Color.FromRgb(4, 180, 208)), 1) : new GradientStop(farbKollektion[0], 1));
				        break;
					case 2:
						gradientCollection.Add(new GradientStop(farbKollektion[0], 0.5));

						var first2 = aptResources.FirstOrDefault();

				        if (first2 != null)
				        {
				            gradientCollection.Add(new GradientStop((Color) (ColorConverter.ConvertFromString(first2.Color) ?? Color.FromRgb(4, 180, 208)), 0.5));
				        }

						break;
					default:
						gradientCollection.Add(new GradientStop(farbe, 1));
						break;
				}

				return new LinearGradientBrush(gradientCollection, new Point(.5, 0), new Point(.5, 1));
			}
			catch (Exception)
			{
				return new LinearGradientBrush(new GradientStopCollection { new GradientStop(farbe, 1) }, new Point(.5, 0), new Point(.5, 1));
			}
		}

		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}

	public class AppointmentBorderZusageConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var customFields = (CustomFieldCollection)value;
			var employeeList = (List<Employee2SchedulerAppointmentDC>) customFields["EmployeeList"];

            return employeeList.Any(e => e.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid) && e.ParticipationAnswer == ParticipationAnswer.Vorbehalt) ? 
                new SolidColorBrush(Color.FromRgb(185, 39, 217)) :
                new SolidColorBrush(Color.FromRgb(192, 255, 208));
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}

	public class NichtNochEinConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (parameter != null && parameter.Equals("GibName"))
			{
				var v = (Employee2SchedulerAppointmentDC) value;

				return v.Employee.DetailDescription;
			}

			if (parameter != null && parameter.Equals("ListenQuelle"))
			{
				var customFields = (CustomFieldCollection) value;
				var employeeList = (List<Employee2SchedulerAppointmentDC>) customFields["EmployeeList"];

				return employeeList;
			}

			var val = (Employee2SchedulerAppointmentDC)value;
			var c = Color.FromRgb(255, 255, 255);

			switch (val.ParticipationAnswer)
			{
				case ParticipationAnswer.Vorbehalt:
					c = Color.FromRgb(185, 39, 217);
					break;
				case ParticipationAnswer.Zusage:
			        c = Color.FromRgb(72, 212, 78);
					break;
				case ParticipationAnswer.Absage:
					c = Color.FromRgb(171, 0, 48);
					break;
			}

			return new SolidColorBrush(c);
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
	}
	#endregion
}
