using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
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.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Threading;

using BeWo.Controls;
using BeWo.Core;
using BeWo.Core.Service;
using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.View.Search;
using BeWo.ViewModel;
using BeWo.ViewModel.ListViewModel;

using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;
using BS.Shared.Services;

using DevExpress.Xpf.Bars;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Docking;
using DevExpress.Xpf.Docking.Platform;
using DevExpress.Xpf.Editors;
using DevExpress.XtraPrinting.Native;

using Microsoft.Win32;

using VerticalAlignment = System.Windows.VerticalAlignment;

namespace BeWo.View.Detail
{
    public partial class ServiceRecordView2
    {
        public static Visibility InsertedOnAndByVisibility
        {
            get
            {
                return BeWoApp.AppSettings.HideServiceRecordInsertedByAndInsertedOn ? Visibility.Collapsed : Visibility.Visible;
            }
        }

        private TextBox grosseDokuTextBox;

        public List<CompactWohnheimDC> AlleWohnheime { get; private set; }

        private GroupOfPeopleView _GroupOfPeopleModalPopUp;

        private readonly Dictionary<DayOfWeek, CheckBox> _DayBoxes = new Dictionary<DayOfWeek, CheckBox>();

        private CompactEmployeeDC _SelectedEmployee;

        private long? _StartSupportConceptOid;

        private ServiceRecordListVM _ViewModel;

        private AssessmentSheetEntryView assessmentSheet;

	    private ServiceRecordVM lastSelectedVM;

        private Dictionary<CompactCustomerDC, List<AssessmentSheetCategoryDC>> customerContainsAssessmentCategories = new Dictionary<CompactCustomerDC, List<AssessmentSheetCategoryDC>>();

        private bool _IgnoreGroupMultiCheck;

	    public static double DocumentationTextBoxFontSize
	    {
			get
			{
				return BeWoApp.AppSettings.DocumentationFontSize;
			}
	    }

        public ServiceRecordView2(ServiceRecordListVM pViewModel, long? startSupportConceptOid)
        {
            InitializeComponent();

            multiSupportConceptControl.AutoGetAllAfterLoaded = false;
            multiSupportConceptControl.EditGroupButtonClicked += multiSupportConceptControl_EditGroupButtonClicked;
            popup_content.Visibility = Visibility.Hidden;

            InsertedByColumn.Visible = !BeWoApp.AppSettings.HideServiceRecordInsertedByAndInsertedOn;
            InsertedOnColumn.Visible = !BeWoApp.AppSettings.HideServiceRecordInsertedByAndInsertedOn;

            _StartSupportConceptOid = startSupportConceptOid;

            ViewModel = pViewModel;

            //if (ViewModel.ServiceRecordTimeInterval == ServiceRecordTimeInterval.LastNDays)
            //{
            //    NDayTextbox.Visibility = Visibility.Visible;
            //    TimeIntervalComboBox.Visibility = Visibility.Collapsed;

            //    NLadenBtn.Visibility = Visibility.Visible;
            //}

			ViewModel.StatisticInfosLoaded += ViewModelOnStatisticInfosLoaded;

            DownloadLinkEngine = new DownloadLinkEngine();
            linkExcelExport.NavigateUri = DownloadLinkEngine.GenerateNewExcelLink();

            chkWithClient.Content = BeWoApp.AppSettings.TimeRecordingMenuName + " für ausgewählten Klienten";
            txtTimeRecording.Text = BeWoApp.AppSettings.TimeRecordingMenuName;

			numerictb_distance.Visibility = BeWoApp.AppSettings.ShowDistanceFields ? Visibility.Visible : Visibility.Collapsed;
			lblDistance.Visibility = BeWoApp.AppSettings.ShowDistanceFields ? Visibility.Visible : Visibility.Collapsed;

	        DistanceGridColumn.Visible = BeWoApp.AppSettings.ShowDistanceFields;

            //this.numerictb_duration.TextChanged += (s, e) =>
            //    {
            //        if (string.IsNullOrEmpty(this.numerictb_duration.Text))
            //        {
            //            this.numerictb_duration.Value = 0;
            //        }
            //    };

            combobox_services.SelectionChanged += (s, e) =>
                {
                    if (combobox_services.SelectedIndex == -1)
                    {
                        combobox_services.SelectedIndex = 0;
                    }
                };

            //combobox_services_wohnheimbuchung.SelectionChanged += (s, e) =>
            //{
            //    if (combobox_services_wohnheimbuchung.SelectedIndex == - 1)
            //    {
            //        combobox_services_wohnheimbuchung.SelectedIndex = 0;
            //    }
            //};

			InitDayCheckBoxes();

            Loaded += ServiceRecordView2_Loaded;

            supportConceptSelectionControl.ControlInitialized += supportConceptSelectionControl_ControlInitialized;

            if (BeWoApp.LoggedOnUser.HasRight(UserRightType.AssessmentSheet_View))
            {
                assessmentSheet = new AssessmentSheetEntryView();
                punktebogenRootGrid.Children.Clear();
                punktebogenRootGrid.Children.Add(assessmentSheet);
                assessmentSheet.Visibility = Visibility.Collapsed;
            } 
            else
            {
                punktebogenRootGrid.Visibility = Visibility.Collapsed;
            }

            if (BeWoApp.AppSettings.ShowServiceRecordGridControl)
            {
                ChkDetailView.IsChecked = true;
                //srListBox.Visibility = Visibility.Hidden;
                //srGridControl.Visibility = Visibility.Visible;
            }
                
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreationForOtherEmployees))
            {
                employeeSearchView.SearchMode = SearchMode.OnlyTeamMember;
            }

	        if (BeWoApp.AppSettings.ShowMarker)
	        {
		        chkContentFilter.Content = "Nur Marker anzeigen";
		        chkContentFilter.Visibility = Visibility.Visible;

		        chkServiceRecordTypeContent.Content = "Marker";
		        chkServiceRecordTypeContent.Visibility = Visibility.Visible;

	        }
	        else
	        {
				if (BeWoApp.Mandator.BeWoClientType == 3)
				{
					//Köln Ring
					chkContentFilter.Visibility = Visibility.Visible;
					chkServiceRecordTypeContent.Visibility = Visibility.Visible;
				}
				else
				{
					chkContentFilter.Visibility = Visibility.Collapsed;
					chkServiceRecordTypeContent.Visibility = Visibility.Collapsed;
				}
	        }

	        if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreatingGroupBooking))
	        {
		        chkGroupBooking.Visibility = Visibility.Collapsed;
	        }
			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreatingMultiBooking))
			{
				chkMultiBooking.Visibility = Visibility.Collapsed;
			}
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineAlleAnsehen) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineNurEigeneAnsehen))
            {
                TextbausteineButton1.Visibility = Visibility.Collapsed;    
                TextbausteineBearbeitenButton1.Visibility = Visibility.Collapsed;
				TextbausteineButton2.Visibility = Visibility.Collapsed;
				TextbausteineBearbeitenButton2.Visibility = Visibility.Collapsed;
				TextbausteineButton3.Visibility = Visibility.Collapsed;
				TextbausteineBearbeitenButton3.Visibility = Visibility.Collapsed;
				TextbausteineButton4.Visibility = Visibility.Collapsed;
				TextbausteineBearbeitenButton4.Visibility = Visibility.Collapsed;
				TextbausteineButton5.Visibility = Visibility.Collapsed;
				TextbausteineBearbeitenButton5.Visibility = Visibility.Collapsed;
            }
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineAlleBearbeiten) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineNurEigeneBearbeiten))
            {
                TextbausteineBearbeitenButton1.Visibility = Visibility.Collapsed;
				TextbausteineBearbeitenButton2.Visibility = Visibility.Collapsed;
				TextbausteineBearbeitenButton3.Visibility = Visibility.Collapsed;
				TextbausteineBearbeitenButton4.Visibility = Visibility.Collapsed;
				TextbausteineBearbeitenButton5.Visibility = Visibility.Collapsed;
            }
	        // gridServiceRecordsSelection.DataSource = pViewModel.VMList;

	        if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecordAllowRebooking))
	        {
				Eintragumbuchunsbutton.Visibility = Visibility.Collapsed;
	        }

            ServiceFacade.DoCustomerServiceAsync(s => s.GetAllActiveWohnheimeCompact(), wohnheime => this.Dispatch(() =>
            {
                chkWohnheimBooking.Visibility = wohnheime.Any() ? Visibility.Visible : Visibility.Collapsed;
            }));

	        SetStatisticsVisibility();

            ConfigureDocTypes();

            ConfigureEndDate();
        }

        private void ConfigureEndDate() {
			
            var Settings = BeWoApp.AppSettings;

            if (Settings.IsEndDateVisible)
            {
                GridMitEnddatum.Visibility = Visibility.Visible;

				startDatum1.Visibility = Visibility.Collapsed;
				datepicker_newDate1.Visibility = Visibility.Collapsed;
				StartzeitLabel1.Visibility = Visibility.Collapsed;
				GridOhneEnddatum.Visibility = Visibility.Collapsed;

				
                EndDatumHeader.Visible = true;
            }
            else
            {
				GridMitEnddatum.Visibility = Visibility.Collapsed;

				startDatum1.Visibility = Visibility.Visible;
				datepicker_newDate1.Visibility = Visibility.Visible;
				StartzeitLabel1.Visibility = Visibility.Visible;
				GridOhneEnddatum.Visibility = Visibility.Visible;

                EndDatumHeader.Visible = false;
            }
        }

        private void ConfigureDocTypes()
        {
            //Tabs und Tabelle
            int i = _ViewModel.AllDocTypes.Count;
			DokumentationLabel.Visibility = System.Windows.Visibility.Collapsed;
            if(i == 0)
            {
                TabItem1_Notice.Header     = "Dokumentation";
                head_Doku1.Header          = "Dokumentation";
                DokumentationLabel.Content = "";

                TabItem2_Notice.Visibility = Visibility.Collapsed;
                TabItem3_Notice.Visibility = Visibility.Collapsed;
                TabItem4_Notice.Visibility = Visibility.Collapsed;
                TabItem5_Notice.Visibility = Visibility.Collapsed;

                head_Doku2.Visible = false;
                head_Doku3.Visible = false;
                head_Doku4.Visible = false;
                head_Doku5.Visible = false;
                
            }
            else if (i == 1) 
            {
                //DokumentationLabel.Content = "Dokumentation";
                TabItem1_Notice.Header     = _ViewModel.AllDocTypes[0].ToString();
                head_Doku1.Header          = _ViewModel.AllDocTypes[0].ToString();

                TabItem2_Notice.Visibility = Visibility.Collapsed;
                TabItem3_Notice.Visibility = Visibility.Collapsed;
                TabItem4_Notice.Visibility = Visibility.Collapsed;
                TabItem5_Notice.Visibility = Visibility.Collapsed;

                head_Doku2.Visible = false;
                head_Doku3.Visible = false;
                head_Doku4.Visible = false;
                head_Doku5.Visible = false;
            }
            else if (i                     == 2) {
                DokumentationLabel.Content = "Dokumentation";
                TabItem1_Notice.Header     = _ViewModel.AllDocTypes[0].ToString();
                TabItem2_Notice.Header     = _ViewModel.AllDocTypes[1].ToString();
                head_Doku1.Header          = _ViewModel.AllDocTypes[0].ToString();
                head_Doku2.Header          = _ViewModel.AllDocTypes[1].ToString();

                TabItem3_Notice.Visibility = Visibility.Collapsed;
                TabItem4_Notice.Visibility = Visibility.Collapsed;
                TabItem5_Notice.Visibility = Visibility.Collapsed;

                head_Doku3.Visible = false;
                head_Doku4.Visible = false;
                head_Doku5.Visible = false;
            }
            else if (i == 3) 
            {
                DokumentationLabel.Content = "Dokumentation";
                TabItem1_Notice.Header = _ViewModel.AllDocTypes[0].ToString();
                TabItem2_Notice.Header = _ViewModel.AllDocTypes[1].ToString();
                TabItem3_Notice.Header = _ViewModel.AllDocTypes[2].ToString();
                head_Doku1.Header = _ViewModel.AllDocTypes[0].ToString();
                head_Doku2.Header = _ViewModel.AllDocTypes[1].ToString();
                head_Doku3.Header = _ViewModel.AllDocTypes[2].ToString();

                TabItem4_Notice.Visibility = Visibility.Collapsed;
                TabItem5_Notice.Visibility = Visibility.Collapsed;

                head_Doku4.Visible = false;
                head_Doku5.Visible = false;
            }
            else if (i == 4) 
            {
                DokumentationLabel.Content = "Dokumentation";

                TabItem1_Notice.Header = _ViewModel.AllDocTypes[0].ToString();
                TabItem2_Notice.Header = _ViewModel.AllDocTypes[1].ToString();
                TabItem3_Notice.Header = _ViewModel.AllDocTypes[2].ToString();
                TabItem4_Notice.Header = _ViewModel.AllDocTypes[3].ToString();

                head_Doku1.Header = _ViewModel.AllDocTypes[0].ToString();
                head_Doku2.Header = _ViewModel.AllDocTypes[1].ToString();
                head_Doku3.Header = _ViewModel.AllDocTypes[2].ToString();
                head_Doku4.Header = _ViewModel.AllDocTypes[3].ToString();

                TabItem5_Notice.Visibility = Visibility.Collapsed;

                head_Doku5.Visible = false;
            }
            else if (i == 5)
            {
                DokumentationLabel.Content = "Dokumentation";

                TabItem1_Notice.Header = _ViewModel.AllDocTypes[0].ToString();
                TabItem2_Notice.Header = _ViewModel.AllDocTypes[1].ToString();
                TabItem3_Notice.Header = _ViewModel.AllDocTypes[2].ToString();
                TabItem4_Notice.Header = _ViewModel.AllDocTypes[3].ToString();
                TabItem5_Notice.Header = _ViewModel.AllDocTypes[4].ToString();

                head_Doku1.Header = _ViewModel.AllDocTypes[0].ToString();
                head_Doku2.Header = _ViewModel.AllDocTypes[1].ToString();
                head_Doku3.Header = _ViewModel.AllDocTypes[2].ToString();
                head_Doku4.Header = _ViewModel.AllDocTypes[3].ToString();
                head_Doku5.Header = _ViewModel.AllDocTypes[4].ToString();
            }
        }

	    private void ViewModelOnStatisticInfosLoaded(object sender, EventArgs eventArgs)
	    {
		    var info = sender as ServiceRecordStatisticsInfoDC;
		    if (info != null)
		    {
				StatisticInfoGrid.Children.Clear();
				StatisticInfoGrid.ColumnDefinitions.Clear();
				StatisticInfoGrid.RowDefinitions.Clear();

			    if (info.Header != null)
			    {
					StatisticInfoGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
				    

				    foreach (var header in info.Header)
				    {
					    StatisticInfoGrid.RowDefinitions.Add(new RowDefinition());
				    }
				    int rowIndex = 0;
				    foreach (var header in info.Header)
				    {
					    var txt = new TextBlock();
					    txt.SetValue(Grid.ColumnProperty, 0);
					    txt.SetValue(Grid.RowProperty, rowIndex);
					    txt.Foreground = new SolidColorBrush((Color) ColorConverter.ConvertFromString(info.ForegroundColor[rowIndex]));
					    txt.Height = 14;
					    txt.Text = header;

					    StatisticInfoGrid.Children.Add(txt);

					    rowIndex++;
				    }
					
				    if (info.PeriodStatisticInfos != null)
				    {
					    foreach (var periodInfo in info.PeriodStatisticInfos)
					    {
							StatisticInfoGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
							StatisticInfoGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
					    }

					    int colIndex = 1;
						foreach (var periodInfo in info.PeriodStatisticInfos)
						{
							rowIndex = 0;
							foreach (var lv in periodInfo.LeftValues)
							{
								if (!String.IsNullOrEmpty(lv))
								{
									var txt = new TextBlock();
									txt.SetValue(Grid.ColumnProperty, colIndex);
									txt.SetValue(Grid.RowProperty, rowIndex);
									txt.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(periodInfo.LeftValueColors[rowIndex]));
									txt.Height = 12;
									txt.FontWeight = FontWeights.Bold;
									txt.Text = lv;
									txt.HorizontalAlignment = HorizontalAlignment.Right;
									txt.Margin = new Thickness(10,0,0,0);
									txt.Padding = new Thickness(1, 0, 1, 0);
									if (String.IsNullOrEmpty(periodInfo.RightValues[rowIndex]))
									{
										txt.SetValue(Grid.ColumnSpanProperty, 2);
									}

									StatisticInfoGrid.Children.Add(txt);

									
									//<TextBlock x:Name="txtStatisticInfoHeader" Grid.Column="0" Grid.Row="0"
                                     //                           Text="{Binding Path=Header}" Grid.ColumnSpan="4"
                                     //                           FontWeight="Bold" FontSize="12" Foreground="{DynamicResource BigInfoTextBrush}" Height="14"/>
								}
								if (!String.IsNullOrEmpty(periodInfo.RightValues[rowIndex]))
								{
									var txt = new TextBlock();
									txt.SetValue(Grid.ColumnProperty, colIndex + 1);
									txt.SetValue(Grid.RowProperty, rowIndex);
									txt.Foreground =
										new SolidColorBrush((Color) ColorConverter.ConvertFromString(periodInfo.RightValueColors[rowIndex]));
									txt.Height = 12;
									txt.FontWeight = FontWeights.Bold;
									txt.Text = periodInfo.RightValues[rowIndex];
									txt.HorizontalAlignment = HorizontalAlignment.Right;
									txt.Margin = new Thickness(10, 0, 0, 0);
									txt.Padding = new Thickness(1, 0, 1, 0);
									StatisticInfoGrid.Children.Add(txt);


									//<TextBlock x:Name="txtStatisticInfoHeader" Grid.Column="0" Grid.Row="0"
									//                           Text="{Binding Path=Header}" Grid.ColumnSpan="4"
									//                           FontWeight="Bold" FontSize="12" Foreground="{DynamicResource BigInfoTextBrush}" Height="14"/>
								}
								

								rowIndex++;
							}

							colIndex += 2;
						}
				    }
			    }
		    }
	    }

	    private void SetStatisticsVisibility()
	    {
		    String tenant = BeWoApp.Tenant;

#if DEBUG
		    //tenant = "3057313346";
#endif

			if (tenant == "3057313346" || tenant == "2918696314")
			{
				lblStatisticInfo1.Text = "Geleistet/bewilligt Gesamt";
				lblStatisticInfo2.Text = "Geleistet/bewilligt pro Woche";
				lblStatisticInfo3.Text = "Geleistet/bewilligt pro Monat";
				lblStatisticInfo4.Text = "Übertrag Monat";
				lblStatisticInfo4.Visibility = Visibility.Visible;
				lblStatisticInfo5.Visibility = Visibility.Collapsed;
			}
			else
			{
				lblStatisticInfo4.Visibility = Visibility.Collapsed;
				lblStatisticInfo5.Visibility = Visibility.Collapsed;
			}
		}

        void supportConceptSelectionControl_ControlInitialized(object sender, EventArgs e)
        {
            InitCustomerSelectedItem();
            multiSupportConceptControl.SupportConceptList = supportConceptSelectionControl.SupportConceptList;
        }

        public override bool CanDelete
        {
            get { return false; }
        }

        public DownloadLinkEngine DownloadLinkEngine { get; set; }

        public override bool IsDirty
        {
            get { return ViewModel != null && ViewModel.AddedCount != 0; }
        }

        public override string Title
        {
            get { return "Zeiterfassung"; }
        }

        public bool WithoutClient
        {
            get { return ViewModel != null && ViewModel.WithoutClient; }

            set
            {
                if (ViewModel != null)
                    ViewModel.WithoutClient = value;
            }
        }

        internal override DependencyObject ValidationOnSaveRootElement
        {
            get { return srListBox; }
        }

        internal ServiceRecordListVM ViewModel
        {
            get { return _ViewModel; }

            set
            {
                _SelectedEmployee = BeWoApp.LoggedOnUser.Employee;
                popupedit_employee.Text = _SelectedEmployee.ToString();

                multiEmployeeControl.SelectedEmployees.Add(_SelectedEmployee);

                DataContext = value;

                SetEmployeeComboVisibility();

                supportConceptSelectionControl.SelectedItem = new FlatSupportConceptTreeNodeDC();
                _ViewModel = value;

                _ViewModel.ServiceRecordListChanged += ViewModel_ServiceRecordListChanged;

                if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecordView_Create) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.CreateAll))
                {
                    newObjectInfoGrid.IsEnabled = false;
                    button_add.IsEnabled = false;
                }

                Unloaded += ServiceRecordView2_Unloaded;
            }
        }

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

            // lAnimation.From = scale.ScaleX;
            // lAnimation.To = pOpacitiy;
            detailContentGrid.BeginAnimation(OpacityProperty, lAnimation);

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

        public override void Delete()
        {
            Delete(GetSelectedServiceRecordFromListBox());
        }

        public void Delete(ServiceRecordVM vm)
        {
            if (vm == null)
            {
                return;
            }

            var msg = vm.GroupOid != null 
                             ? "ACHTUNG, wenn Sie fortfahren, löschen Sie die gesamte Gruppenbuchung.\nWenn Sie nur einzelne Klienten aus der Gruppe entfernen möchten,\neditieren Sie die Gruppe und entfernen den Klienten aus der Liste aller Hilfepläne.\nSind Sie sicher, dass Sie dem gesamten Gruppeneintrag löschen möchten?" 
                             : "Sind Sie sicher, dass Sie den gewählten Eintrag löschen möchten?";

            if (MessageBox.Show(msg, "Eintrag löschen", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes) 
                return;

            if (vm.GroupOid != null)
            {
                var deletedVMs = new List<ServiceRecordVM>();

                foreach (var item in ViewModel.VMList)
                {
                    if (item.GroupOid != null && item.GroupOid.Value == vm.GroupOid.Value)
                    {
                        deletedVMs.Add(item);
                    }
                }

                foreach (var deletedVM in deletedVMs)
                {
                    ViewModel.VMList.Remove(deletedVM);
                }
            }
            else
            {
                bool test = ViewModel.VMList.Remove(vm);
            }

            var lDC = vm.CommitToDataContract();
            ServiceFacade.DoOperationsServiceAsync(s => s.DeleteServiceRecord(lDC.ServiceRecordOid.Value, lDC.ServiceRecordVersion.Value), RefreshGrid);

            // gridServiceRecordsSelection.UpdateLayout();
            // gridServiceRecordsSelection.DataSource = ViewModel.VMList; 
        }

        public ServiceRecordVM GetSelectedServiceRecordFromListBox()
        {
            return (ServiceRecordVM) srListBox.SelectedItem;
        }

        public void SetSelectedServiceRecordVM(ServiceRecordVM vm)
        {
	        if (vm != null)
	        {
		        ServiceRecordVM existingVm = null;

		        foreach (var serviceRecordVm in ViewModel.VMList)
		        {
			        if (serviceRecordVm.Id == vm.Id)
			        {
			            existingVm = serviceRecordVm;
			        }
		        }

		        srListBox.SelectedItem = existingVm;
		        srTableView.FocusedRow = existingVm;
	        }
        }

        protected override void Save()
        {
            var lToDos = new List<Action<IOperationsService>>();

            if (ViewModel.AddedCount > 0)
            {
                lToDos.Add(
                    s =>
                        {
                            var newItems = ViewModel.CommitAdded();
                            try
                            {
                                var oids = s.InsertNewServiceRecords(newItems);
                                var idx = 0;

                                foreach (var vm in ViewModel.VMList)
                                {
                                    if (!vm.IsNew)
                                    {
                                        continue;
                                    }

                                    vm.IsNew = false;
                                    vm.DataContract.ServiceRecordVersion = 1;
                                    vm.DataContract.ServiceRecordOid = oids[idx++];
                                }
                            }
                            catch (Exception)
                            {
                                var newVMs = ViewModel.VMList.Where(vm => vm.IsNew).ToList();

                                foreach (var serviceRecordVm in newVMs)
                                {
                                    ViewModel.VMList.Remove(serviceRecordVm);
                                }

                                this.Dispatch(() => ViewModel.RefreshServiceRecordsForSelectedTreeNode());
                                
                                throw;
                            }
                    });
            }

            ServiceFacade.DoMultipleOperationsServicesSync(lToDos);
	        ReloadViewModel();
        }

        internal override bool DoSaveCheck()
        {
			BeWoApp.SaveAppSettings();

            if (!String.IsNullOrEmpty(ViewModel.PrototypeVM.Notice))
            {
                var lResult = ShowSaveQuestion();
                if (lResult == MessageBoxResult.Cancel)
                {
                    return false;
                }

                if (lResult == MessageBoxResult.Yes)
                {
                    return SaveServiceRecord();
                }
            }

            return true;
        }

        private void ClosePopupView()
        {
            SetPopupViewVisible(false);
            popup_content.Child = null;
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.VMList.Remove((ServiceRecordVM) ((Button) sender).Tag);
            Save();
        }

        private void Edit(ServiceRecordVM vm)
        {
            if (vm == null || !vm.EditAllowed)
            {
                return;
            }

            BeWoView serviceRecordEditView;

            if (vm.GroupOid != null)
            {
                serviceRecordEditView = new ServiceRecordGroupEditView();
            }
            else
            {
                serviceRecordEditView = new ServiceRecordEditView();
            }

            popup_content.Child = serviceRecordEditView;
            
			double height = 500;
			double width  = 800;

			popup_content.Child = serviceRecordEditView;

			if (rootGrid.ActualWidth < width)
			{
			    width = rootGrid.ActualWidth;
			}
			if (rootGrid.ActualHeight < height)
			{
			    height = rootGrid.ActualHeight;
			}
			
			popup_content.Width = width;
			popup_content.Height = height;

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

                                ClosePopupView();
                                ViewModel.RefreshServiceRecordsForSelectedTreeNode();
                                SetSelectedServiceRecordVM(vm);
                            }));
                serviceRecordEditView.CommandBindings.Add(
                    new CommandBinding(
                        ApplicationCommands.Save,
                        (s, e) =>
                            {
                                bool save;
                                if (serviceRecordEditView is ServiceRecordEditView)
                                {
                                    save = ((ServiceRecordEditView)serviceRecordEditView).IsValid() && ((ServiceRecordEditView)serviceRecordEditView).IsCustomerChangeAllowed();
                                }
                                else
                                {
                                    save = ((ServiceRecordGroupEditView)serviceRecordEditView).IsValid() && ((ServiceRecordGroupEditView)serviceRecordEditView).IsCustomerChangeAllowed();
                                }

                                if (!save)
                                {
                                    return;
                                }

                                serviceRecordEditView.SaveData();
                                ClosePopupView();

                                if (!(serviceRecordEditView is ServiceRecordEditView))
                                {
                                    return;
                                }

								ViewModel.BuildServiceRecordsForSelectedTreeNode(true, RefreshFinished);
	                            lastSelectedVM = vm;
                            }));
            }

            if (serviceRecordEditView is ServiceRecordEditView)
            {
                ((ServiceRecordEditView)serviceRecordEditView).InitView(ViewModel, vm, WithoutClient);
                serviceRecordEditView.ParentView = this;
                SetPopupViewVisible(true);
            }
            else
            {
                ServiceFacade.DoOperationsServiceAsync(
                    s => s.GetServiceRecordGroup(vm.GroupOid.Value),
                    r => this.Dispatch(
                        delegate
                            {
                                ((ServiceRecordGroupEditView)serviceRecordEditView).InitView(ViewModel, vm, r);

                                serviceRecordEditView.ParentView = this;
                                popup_content.Width += 190;
                                SetPopupViewVisible(true);
                            }));
            }
        }
		
		private void RefreshFinished()
		{
			SetSelectedServiceRecordVM(lastSelectedVM);
		}

        private void ShowHistory(ServiceRecordVM vm)
        {
            if (vm == null)
            {
                return;
            }

            double height = 600;
			double width  = 1200;

            var serviceRecordHistoryView = new ServiceRecordHistoryView();

            popup_content.Child = serviceRecordHistoryView;
            

            if (rootGrid.ActualHeight < height)
            {
                height = rootGrid.ActualHeight;
            }
			if (rootGrid.ActualWidth < width)
			{
			    width = rootGrid.ActualWidth;
			}

            popup_content.Height = height;
			popup_content.Width = width;

            if (serviceRecordHistoryView.CommandBindings.Count == 0)
            {
                serviceRecordHistoryView.CommandBindings.Add(
                    new CommandBinding(
                        ApplicationCommands.Close,
                        (s, e) => ClosePopupView()));

            }

            ServiceFacade.DoOperationsServiceAsync(
                s => s.GetServiceRecordHistory(vm.DataContract.ServiceRecordOid.Value),
                r => this.Dispatch(
                    delegate
                        {
                            serviceRecordHistoryView.InitView(r);

                            serviceRecordHistoryView.ParentView = this;
                            SetPopupViewVisible(true);
                        }));
        }

        private void EmployeeSearchView_CustomerSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            _SelectedEmployee       = e.Data;
            popupedit_employee.Text = _SelectedEmployee.ToString();
            popup_employee.IsOpen   = false;

            ViewModel.SelectedEmployee = _SelectedEmployee;

            if (WithoutClient)
            {
                SelectedItemChanged(null);
            }
        }

        private static ChildItem FindVisualChild<ChildItem>(DependencyObject obj) where ChildItem : DependencyObject
        {
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is ChildItem)
                {
                    return (ChildItem)child;
                }

                var childOfChild = FindVisualChild<ChildItem>(child);

                if (childOfChild != null)
                {
                    return childOfChild;
                }
            }

            return null;
        }

        private void InitCustomerSelectedItem()
        {
            if (_StartSupportConceptOid != null)
            {
                supportConceptSelectionControl.SetSelectedSupportConceptOid(_StartSupportConceptOid.Value);
                _StartSupportConceptOid = null;
            }
        }

        private void InitDayCheckBoxes()
        {
            foreach (var iDay in Utils.GetDayOfWeeks(DayOfWeek.Monday))
            {
                var lCb = new CheckBox
                              {
                                  Content = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedDayName(iDay), 
                                  Margin = new Thickness(3), 
                                  IsHitTestVisible = DateTime.Now.DayOfWeek != iDay
                              };

                _DayBoxes[iDay] = lCb;
                wrapPanel_days.Visibility = Visibility.Collapsed;
                wrapPanel_days.Children.Add(lCb);

                lCb.Checked += (s, e) => ViewModel.RecordingDays.Add(_DayBoxes.Single(entry => entry.Value == s).Key);
                lCb.Unchecked += (s, e) => ViewModel.RecordingDays.Remove(_DayBoxes.Single(entry => entry.Value == s).Key);

                lCb.IsChecked = DateTime.Now.DayOfWeek == iDay;
            }

            DependencyPropertyDescriptor.FromProperty(DateEdit.EditValueProperty, typeof(DateEdit)).AddValueChanged(
                datepicker_newDate1,
                (s, e) => _DayBoxes.DoForEach(
                    iCheck =>
                        {
                            iCheck.Value.IsChecked = datepicker_newDate1.EditValue != null && iCheck.Key == datepicker_newDate1.DateTime.DayOfWeek;
                            iCheck.Value.IsHitTestVisible = !iCheck.Value.IsChecked.Value;
                            iCheck.Value.IsEnabled = iCheck.Value.IsHitTestVisible;
                        }));


        }

        private static bool IsPartOf(object p, Type type)
        {
            if (p != null)
            {
                var fe = p as FrameworkElement;
                if (fe != null)
                {
                    return fe.GetType() == type || IsPartOf(fe.TemplatedParent, type);
                }
            }

            return false;
        }

        private void RefreshGrid()
        {
            Dispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                (Action) delegate
                             {
                                 var selected = GetSelectedServiceRecordFromListBox();
                                 ViewModel.RefreshServiceRecordsForSelectedTreeNode();
                                 SetSelectedServiceRecordVM(selected);
                             });
        }

	    private void ReloadViewModel()
	    {
		    ViewModel.PrototypeVM.Notice = string.Empty;
			ViewModel.PrototypeVM.Notice2 = string.Empty;
			ViewModel.PrototypeVM.Notice3 = string.Empty;
			ViewModel.PrototypeVM.Notice4 = string.Empty;
			ViewModel.PrototypeVM.Notice5 = string.Empty;

		    SetDefaultCategory();

	        if (ViewModel.PrototypeVM.GoalTree != null && ViewModel.PrototypeVM.GoalTree.Count > 0)
	        {
	            foreach (var item in ViewModel.PrototypeVM.GoalTree)
	            {
	                item.IsChecked = false;
	            }
	        }

	        ViewModel.PrototypeVM.DistanceInMeter = null;
	    }

		private void SetDefaultCategory()
		{
			if (ViewModel.PrototypeVM.SortedCategories != null)
			{
				foreach (var cat in ViewModel.PrototypeVM.SortedCategories.Where(cat => cat.IsDefault))
				{
				    ViewModel.PrototypeVM.Category = cat;
				}
			}

			if (ViewModel.PrototypeVM.PossibleServiceDescriptions != null)
			{
				foreach (var sd in ViewModel.PrototypeVM.PossibleServiceDescriptions.Where(sd => sd.IsDefault))
				{
				    ViewModel.PrototypeVM.ServiceDescription = sd;
				}
			}
		}

	    private bool SaveGroupBooking()
        {
            var lValid = true;

            if (multiSupportConceptControl.SelectedSupportConcepts.Count == 0)
            {
                MessageBox.Show("Bitte wählen Sie mindestens einen Klienten aus, für den Sie eine Gruppenbuchung anlegen möchten.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                lValid = false;
            }

            if (lValid)
            {
                if (multiEmployeeControl.SelectedEmployees.Count == 0)
                {
                    MessageBox.Show("Bitte wählen Sie mindestens einen Mitarbeiter aus, für den Sie eine Gruppenbuchung anlegen möchten.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                    lValid = false;
                }
            }

			var employeeOids = multiEmployeeControl.SelectedEmployees.Select(compactEmployeeDc => compactEmployeeDc.EmployeeOid).ToList();

	        var cb2scOids = (from scDc in multiSupportConceptControl.SelectedSupportConcepts where scDc.CostBearerRelOids != null && scDc.CostBearerRelOids.Count > 0 select scDc.CostBearerRelOids[0]).ToList();

	        foreach (var node in from dc in multiSupportConceptControl.SelectedSupportConcepts where lValid select SupportConceptService.CreateFlatSupportConceptItem(dc, null))
            {
				lValid = BeWoUtils.ValidateServiceRecordVM(ViewModel.PrototypeVM, null, node, WithoutClient, ViewModel.SelectedEmployee, employeeOids, cb2scOids);
            }

            if (lValid)
            {
                var list = ViewModel.CreateFromPrototype();

                if (list.Count > 0)
                {
                    var prototypeVM = list[0];

                    var personCount = multiSupportConceptControl.SelectedSupportConcepts.Count;
                    var employeeCount = multiEmployeeControl.SelectedEmployees.Count;

                    prototypeVM.GroupEmployeeCount = employeeCount;
                    prototypeVM.GroupPersonCount = personCount;


                    // Runden
                    var roundDuration = false;
                    var minuteInterval = 0;
	                String calcId = null;
                    var lastMinuteInterval = -1;

	                if (prototypeVM.ServiceDescription.Category.IsBillable)
	                {
		                roundDuration = true;
		                foreach (var org in from dc in multiSupportConceptControl.SelectedSupportConcepts
			                where dc.CostBearerList.Count > 0
			                select dc.CostBearerList[0].Organisation)
		                {
			                if (org != null)
			                {
				                minuteInterval = org.ActualMinuteIntervall;


				                if (lastMinuteInterval == -1)
				                {
					                lastMinuteInterval = minuteInterval;
					                calcId = org.CostBearerID;
				                }
				                else if (lastMinuteInterval != minuteInterval)
				                {
					                roundDuration = false;
				                }
			                }
			                else if (minuteInterval >= 0)
			                {
				                roundDuration = false;
			                }
			                else
			                {
				                minuteInterval = 0;
			                }
		                }
	                }


	                decimal duration = prototypeVM.RoundedDuration;
                    decimal totalDuration = duration;


					GroupDurationDC gd = ServiceRecordListVM.CalculateGroupDuration(personCount, employeeCount, totalDuration, cb2scOids);

		            if (gd != null)
		            {
						prototypeVM.GroupRoundedDuration = gd.TotalDuration;
						prototypeVM.RoundedDuration = gd.SingleDuration;
		            }
		            else
		            {
						if (personCount > 2 && (BeWoApp.Tenant == "9893557471") || (BeWoApp.Tenant == "2918696314")) //Caritas Frankfurt
						{
							prototypeVM.GroupRoundedDuration = totalDuration;
							prototypeVM.RoundedDuration = ((totalDuration * employeeCount) / personCount) + 10;
						}
						else if (personCount > 1 && BeWoApp.Tenant == "5653806613") //Feid&Kollegen
						{
							prototypeVM.GroupRoundedDuration = totalDuration;
							prototypeVM.RoundedDuration = ((totalDuration * employeeCount) / personCount);
								
						}
						else
						{
							if (minuteInterval > 0 && roundDuration)
							{
								Calculations calc = Calculations.GetInstance(calcId);
								totalDuration = calc.GetRoundedDuration(minuteInterval, duration);
							}

							prototypeVM.RoundedDuration = Math.Round(totalDuration / personCount, 0, MidpointRounding.AwayFromZero);
							prototypeVM.GroupRoundedDuration = totalDuration;

							if (BeWoApp.Tenant == "0216265667") //Lebenshilfe Hannover
							{
								prototypeVM.RoundedDuration += 10;
							}
							
						}        
		            }
	                
                    ServiceRecordVM newVM;
                    var newVMList = new List<ServiceRecordVM>();


                    foreach (CompactSupportConceptDC dc in multiSupportConceptControl.SelectedSupportConcepts)
                    {
                        var addToList = true;
                        foreach (CompactEmployeeDC emp in multiEmployeeControl.SelectedEmployees)
                        {
                            newVM = prototypeVM.Clone();

                            newVM.Employee = emp;
                            newVM.ChoosenNode = SupportConceptService.CreateFlatSupportConceptItem(dc, null);
                            newVM.SetInsertedOn(DateTime.Now);
                            newVMList.Add(newVM);

                            if (!addToList) 
                                continue;

                            // ###AddServiceRecord
                            ViewModel.VMList.Add(newVM);
                            addToList = false;
                        }
                    }

                    var lToDos = new List<Action<IOperationsService>>();

                    if (newVMList.Count > 0)
                    {
                        var dcList = newVMList.Select(item => item.CommitToDataContract()).ToList();

                        if (newVMList.Count == 1)
                        {
                            lToDos.Add(
                                s =>
                                {
                                    List<long> oids = s.InsertNewServiceRecords(dcList);
                                    int idx = 0;
                                    foreach (ServiceRecordVM vm in newVMList)
                                    {
                                        vm.IsNew = false;
                                        vm.DataContract.ServiceRecordVersion = 1;
                                        vm.DataContract.ServiceRecordOid = oids[idx++];
                                    }
                                });
                        }
                        else
                        {
                            var groupDC = new ServiceRecordGroupDC
                                              {
                                                  CustomerCount = personCount, 
                                                  EmployeeCount = employeeCount, 
                                                  StartDate = prototypeVM.StartTime, 
                                                  EndDate = prototypeVM.EndTime, 
                                                  Notice = prototypeVM.Notice
                                              };

                            if (prototypeVM.GroupRoundedDuration != null)
                                groupDC.RoundedDuration = prototypeVM.GroupRoundedDuration.Value;

                            groupDC.ServiceRecordList = dcList;

                            lToDos.Add(
                                s =>
                                {
                                    ServiceRecordGroupDC newGroupDC = s.InsertNewServiceRecordGroup(groupDC);

                                    int idx = 0;
                                    foreach (ServiceRecordVM vm in newVMList)
                                    {
                                        ServiceRecordDC newDC = newGroupDC.ServiceRecordList[idx++];
                                        vm.IsNew = false;
                                        vm.DataContract.ServiceRecordVersion = newDC.ServiceRecordVersion;
                                        vm.DataContract.ServiceRecordOid = newDC.ServiceRecordOid;
                                        vm.DataContract.GroupOid = newGroupDC.ServiceRecordGroupOid;
                                        vm.GroupOid = newGroupDC.ServiceRecordGroupOid;
                                    }
                                });
                        }
                    }

                    ServiceFacade.DoMultipleOperationsServicesAsync(lToDos, UpdateViewModel);

                    MessageBox.Show("Die Gruppenbuchung wurde erfolgreich gespeichert.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }

            return lValid;
        }

        private bool SaveMultiBooking()
        {
            var lValid = true;

            if (multiSupportConceptControl.SelectedSupportConcepts.Count == 0)
            {
                MessageBox.Show("Bitte wählen Sie mindestens einen Hilfeplan aus, für den Sie eine Mehrfachbuchung anlegen möchten.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                lValid = false;
            }

            if (lValid)
            {
                if (multiEmployeeControl.SelectedEmployees.Count == 0)
                {
                    MessageBox.Show("Bitte wählen Sie mindestens einen Mitarbeiter aus, für den Sie eine Mehrfachbuchung anlegen möchten.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                    lValid = false;
                }
            }

			List<long> employeeOids = new List<long>();
			foreach (var compactEmployeeDc in multiEmployeeControl.SelectedEmployees)
			{
				employeeOids.Add(compactEmployeeDc.EmployeeOid);
			}

			List<long> cb2scOids = new List<long>();
			foreach (var scDc in multiSupportConceptControl.SelectedSupportConcepts)
			{
				if (scDc.CostBearerRelOids != null && scDc.CostBearerRelOids.Count > 0)
				{
					cb2scOids.Add(scDc.CostBearerRelOids[0]);
				}
			}

            foreach (FlatSupportConceptTreeNodeDC node in from dc in multiSupportConceptControl.SelectedSupportConcepts where lValid select SupportConceptService.CreateFlatSupportConceptItem(dc, null))
				lValid = BeWoUtils.ValidateServiceRecordVM(ViewModel.PrototypeVM, null, node, true, ViewModel.SelectedEmployee, employeeOids, cb2scOids);
                //lValid = ValidateServiceRecordVMClientX(ViewModel.PrototypeVM, node, true);
                

            if (lValid)
            {
                List<ServiceRecordVM> list = ViewModel.CreateFromPrototype();

                if (list.Count > 0)
                {
                    ServiceRecordVM prototypeVM = list[0];

                    ServiceRecordVM newVM = null;
                    List<ServiceRecordVM> newVMList = new List<ServiceRecordVM>();

					var vmDuration = prototypeVM.RoundedDuration;
                    foreach (CompactSupportConceptDC dc in this.multiSupportConceptControl.SelectedSupportConcepts)
                    {
						decimal duration = vmDuration;
						
						if (dc.CostBearerList.Count > 0)
						{
							var org = dc.CostBearerList[0].Organisation;
							if (org != null)
							{
								Calculations calc = Calculations.GetInstance(org.CostBearerID);

								prototypeVM.RoundedDuration = calc.GetRoundedDuration(org, duration);
							}
						}


                        bool addToList = true;
                        foreach (CompactEmployeeDC emp in this.multiEmployeeControl.SelectedEmployees)
                        {
                            newVM = prototypeVM.Clone();

                            newVM.Employee = emp;
                            newVM.ChoosenNode = SupportConceptService.CreateFlatSupportConceptItem(dc, null);
                            newVM.SetInsertedOn(DateTime.Now);
                            newVMList.Add(newVM);

                            if (addToList)
                            {
                                // ###AddServiceRecord
                                this.ViewModel.VMList.Add(newVM);
                                addToList = false;
                            }
                        }
                    }

                    var lToDos = new List<Action<IOperationsService>>();

                    if (newVMList.Count > 0)
                    {
                        var dcList = newVMList.Select(item => item.CommitToDataContract()).ToList();

                        lToDos.Add(
                            s =>
                                {
                                    List<long> oids = s.InsertNewServiceRecords(dcList);
                                    int idx = 0;
                                    foreach (ServiceRecordVM vm in newVMList)
                                    {
                                        vm.IsNew = false;
                                        vm.DataContract.ServiceRecordVersion = 1;
                                        vm.DataContract.ServiceRecordOid = oids[idx++];
                                    }
                                });

                    }
                

                    ServiceFacade.DoMultipleOperationsServicesAsync(lToDos, UpdateViewModel);

                    MessageBox.Show("Die Dokumentationen wurde erfolgreich gespeichert.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }

            return lValid;
        }

        private bool SaveSingleBooking()
        {
            var lValid = true;

            FlatSupportConceptTreeNodeDC selectedNode = null;
            if (ViewModel.CustomerNodes.Count > 0)
                selectedNode = ViewModel.CustomerNodes[0];

            if (!WithoutClient && (selectedNode == null || selectedNode.SupportConceptTreeNodeDC == null))
            {
                MessageBox.Show("Bitte wählen Sie zuerst einen Hilfeplan, für den Sie Leistungen dokumentieren möchten.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                lValid = false;
            }

            if (lValid)
            {
				lValid = BeWoUtils.ValidateServiceRecordVM(ViewModel.PrototypeVM, ViewModel.StatisticsDC, selectedNode, WithoutClient, ViewModel.SelectedEmployee, null, null);

                if (lValid)
                {
                    var save = false;
                    foreach (var iVM in ViewModel.CreateFromPrototype())
                    {
                        iVM.Employee = _SelectedEmployee;

                        ViewModel.VMList.Add(iVM);
                        save = true;
                    }

                    if (save)
                    {
                        Save();
                        ViewModel.RefreshServiceRecordsForSelectedTreeNode();
                    }
                }
            }

            return lValid;
        }

        private void SelectedItemChanged(FlatSupportConceptTreeNodeDC selectedNode)
        {
            if (ViewModel == null) 
                return;

            UpdateAssessmentSheet(selectedNode);

            ViewModel.ChangeTreeItemSelection(selectedNode);
            srListBox.SelectedIndex = -1;
            
            var sv = FindVisualChild<ScrollViewer>(srListBox);
            if (sv != null)
                sv.ScrollToTop();

            UpdateServiceRecordListReportUrl(selectedNode);

	        SetDefaultCategory();
        }

        private void ServiceRecordView2_Loaded(object sender, RoutedEventArgs e)
        {
			ReloadViewModel();

	        if (ActualHeight > 0)
	        {
		        ComboBoxTreeViewControl.ParentWindowHeight = ActualHeight;
	        }

	        supportConceptSelectionControl.Focus();
        }

        private static void ServiceRecordView2_Unloaded(object sender, RoutedEventArgs e)
        {
            BeWoApp.SaveAppSettings();
        }

        private void SetEmployeeComboVisibility()
        {
            if ((!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreationForOtherEmployees) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreationForOtherTeamMember)) 
                || chkGroupBooking.IsChecked.Value || chkMultiBooking.IsChecked.Value)
            {
                lblEmployee.Visibility        = Visibility.Collapsed;
                popupedit_employee.Visibility = Visibility.Collapsed;
            }
            else
            {
                lblEmployee.Visibility        = Visibility.Visible;
                popupedit_employee.Visibility = Visibility.Visible;
            }
        }

        private void SetPopupViewVisible(bool visible)
        {
            popup_content.Visibility = visible ? Visibility.Visible : Visibility.Hidden;

            if (visible)
            {
                AnimateOpacity(0.5, 200);
            }
            else
            {
                AnimateOpacity(1, 100);
            }
        }

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            var vm = ((TextBox)sender).Tag as ServiceRecordVM;
            if (vm != null)
                srListBox.SelectedItem = vm;
        }

        private void UpdateServiceRecordListReportUrl(FlatSupportConceptTreeNodeDC selectedNode)
        {
            long scOid    = 0;
            long cOid     = 0;
            long cb2scOid = 0;
            var eOid      = BeWoApp.LoggedOnUser.Employee.EmployeeOid;

	        if (selectedNode != null && selectedNode.SupportConceptTreeNodeDC != null)
	        {
		        if (selectedNode.SupportConceptTreeNodeDC.SupportConcept != null)
		        {
		            scOid = selectedNode.SupportConceptTreeNodeDC.SupportConcept.SupportConceptOid;
		        }

		        if (selectedNode.SupportConceptTreeNodeDC.Customer != null)
		        {
		            cOid = selectedNode.SupportConceptTreeNodeDC.Customer.CustomerOid;
		        }

		        if (selectedNode.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC != null)
		        {
		            cb2scOid = selectedNode.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.CostBearer2SupportConceptOid.Value;
		        }
	        }
	        else
	        {
		        if (_SelectedEmployee != null)
		        {
			        eOid = _SelectedEmployee.EmployeeOid;
		        }
	        }

            var url = BeWoApp.SiteOfOrigin + "/ReportView.aspx" + "?eOid=" + eOid + "&scOid=" + scOid + "&cOid=" + cOid + "&cb2scOid=" + cb2scOid + "&type=" + Utils.EnumName(ReportTypes.ServiceRecordList);
            url = BeWoWpfUtils.GetHTMLEncodedURL(url);

            linkPdfExport.NavigateUri = new Uri(url);
        }

        private void UpdateViewModel()
        {
            this.Dispatch(
                delegate
                {
                    ReloadViewModel();
                    ViewModel.RefreshServiceRecordsForSelectedTreeNode();
                });
        }
		

	    private void ViewModel_ServiceRecordListChanged(object sender, EventArgs e)
        {
            var list = _ViewModel.ServiceRecordsForSelectedCustomer.OrderByDescending(srVM => srVM.DateAndTime).ToList();

            foreach (var a in list.Where(a => a.ServiceRecordType == ServiceRecordTypeId.AdditionalService))
            {
                a.EditAllowed = false;
                a.DeleteAllowed = false;
                a.Notice = string.Empty;
            }

            srListBox.ItemsSource = list;
            //###Bars
            srGridControl.ItemsSource = list;
            //this.serviceRecordScheduler.ServiceRecordList = list;

            if (assessmentSheet != null)
                assessmentSheet.ServiceRecords = list;
        }

        private void BtnDelete_Click(object sender, RoutedEventArgs e)
        {
            var vm = ((Button)sender).Tag as ServiceRecordVM;
            if (vm != null)
            {
                srListBox.SelectedItem = vm;
            }

            Delete();
        }

        private void BtnEdit_Click(object sender, RoutedEventArgs e)
        {
            var vm = ((Button) sender).Tag as ServiceRecordVM;

            if (vm != null)
            {
                srListBox.SelectedItem = vm;
            }

			StartEdit(GetSelectedServiceRecordFromListBox());
        }

        private void ServiceRecordListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (IsPartOf(e.OriginalSource, typeof(ScrollBar)))
            {
                return;
            }

			StartEdit(GetSelectedServiceRecordFromListBox());
        }

		private void StartEdit(ServiceRecordVM selectedRecord)
        {
			if (selectedRecord != null)
			{
				var serviceRecordOid = Convert.ToInt64(selectedRecord.Id);

				var record = ServiceFacade.DoOperationsServiceSync(s => s.GetServiceRecordById(serviceRecordOid));

				if (record == null)
				{
					MessageBox.Show("Der ausgewählte Eintrag wurde in der Zwischenzeit gelöscht.", "Editieren nicht möglich", MessageBoxButton.OK, MessageBoxImage.Error);
					ViewModel.RefreshServiceRecordsForSelectedTreeNode();
					return;
				}

				var sr = new ServiceRecordVM(record, ViewModel.PrototypeVM.Category2Services, selectedRecord.AllGoalCategories, selectedRecord.AllGoals);
				
				Edit(sr);
			}
        }

        private void BtnShowHistory_Click(object sender, RoutedEventArgs e)
        {
            var vm = ((Button) sender).Tag as ServiceRecordVM;
            if (vm != null)
            {
                srListBox.SelectedItem = vm;
            }

            ShowHistory(GetSelectedServiceRecordFromListBox());
        }

        private void Button_add_Click(object sender, RoutedEventArgs e)
        {
            SaveServiceRecord();
        }

        private bool SaveServiceRecord()
        {
            var lValid = ValidationTrigger.Validate(root, new Collection<string> { "BedarfsmedikationsGrid" });

            if (lValid)
            {
                if (chkGroupBooking.IsChecked != null && chkGroupBooking.IsChecked.Value)
                {
                    lValid = SaveGroupBooking();
                }
                else if (chkMultiBooking.IsChecked != null && chkMultiBooking.IsChecked.Value)
                {
                    lValid = SaveMultiBooking();
                }
                else
                {
                    lValid = SaveSingleBooking();

                    ComboBoxTreeViewControl.ResetControl();
                    ComboBoxTreeViewControl.TreeViewSourceList = ViewModel.PrototypeVM.GoalTree;
                }
            }

            return lValid;
        }

		private void SetRebookingButtonVisibility()
		{
			if (Eintragumbuchunsbutton == null)
			{
				return;
			}

			var erg = chkWithClient != null && chkWithClient.IsChecked != null && chkWithClient.IsChecked.Value &&
					  chkGroupBooking != null && chkGroupBooking.IsChecked != null && !chkGroupBooking.IsChecked.Value &&
					  chkMultiBooking != null && chkMultiBooking.IsChecked != null && !chkMultiBooking.IsChecked.Value;

			Eintragumbuchunsbutton.Visibility = erg ?
				Visibility.Visible :
				Visibility.Collapsed;
		}

        private void ChkGroupBooking_Checked(object sender, RoutedEventArgs e)
        {
            if (_IgnoreGroupMultiCheck)
            {
                return;
            }

            if (ViewModel != null)
            {
                ViewModel.IsGroupBooking = true;
            }

            supportConceptSelectionControl.Visibility = Visibility.Collapsed;
            multiSupportConceptControl.Visibility     = Visibility.Visible;
            multiEmployeeControl.Visibility           = Visibility.Visible;
            panelGoalLabel.Visibility                 = Visibility.Collapsed;
            panelGoalTree.Visibility                  = Visibility.Collapsed;

            SetEmployeeComboVisibility();

			SetRebookingButtonVisibility();

            if (chkWithClient != null)
            {
                chkWithClient.IsEnabled = false;
            }

            if (chkMultiBooking != null)
            {
                _IgnoreGroupMultiCheck    = true;
                chkMultiBooking.IsChecked = false;
                _IgnoreGroupMultiCheck    = false;
            }

            SelectedItemChanged(SupportConceptService.CreateFlatSupportConceptItem(multiSupportConceptControl.SelectedItem, null));
        }

        private void ChkGroupBooking_Unchecked(object sender, RoutedEventArgs e)
        {
            if (_IgnoreGroupMultiCheck)
            {
                return;
            }

            if (ViewModel != null)
            {
                ViewModel.IsGroupBooking = false;
            }

            supportConceptSelectionControl.Visibility = Visibility.Visible;
            multiSupportConceptControl.Visibility     = Visibility.Collapsed;
            multiEmployeeControl.Visibility           = Visibility.Collapsed;
            panelGoalLabel.Visibility                 = Visibility.Visible;
            panelGoalTree.Visibility                  = Visibility.Visible;

            SetEmployeeComboVisibility();
			SetRebookingButtonVisibility();

            if (chkWithClient != null)
            {
                chkWithClient.IsEnabled = true;
            }

            SelectedItemChanged(supportConceptSelectionControl.SelectedItem);
        }

        private void ChkMultiBooking_Checked(object sender, RoutedEventArgs e)
        {
            if (_IgnoreGroupMultiCheck)
            {
                return;
            }

            if (ViewModel != null)
            {
                ViewModel.IsMultiBooking = true;
            }

            supportConceptSelectionControl.Visibility = Visibility.Collapsed;
            multiSupportConceptControl.Visibility     = Visibility.Visible;
            multiEmployeeControl.Visibility           = Visibility.Visible;
            panelGoalLabel.Visibility                 = Visibility.Collapsed;
            panelGoalTree.Visibility                  = Visibility.Collapsed;

            SetEmployeeComboVisibility();
			SetRebookingButtonVisibility();

            if (chkWithClient != null)
            {
                chkWithClient.IsEnabled = false;
            }

            if (chkGroupBooking != null)
            {
                _IgnoreGroupMultiCheck = true;
                chkGroupBooking.IsChecked = false;
                _IgnoreGroupMultiCheck = false;
            }

            SelectedItemChanged(SupportConceptService.CreateFlatSupportConceptItem(multiSupportConceptControl.SelectedItem, null));
        }

        private void chkMultiBooking_Unchecked(object sender, RoutedEventArgs e)
        {
            if (_IgnoreGroupMultiCheck)
            {
                return;
            }

            if (ViewModel != null)
            {
                ViewModel.IsMultiBooking = false;
            }

            supportConceptSelectionControl.Visibility = Visibility.Visible;
            multiSupportConceptControl.Visibility     = Visibility.Collapsed;
            multiEmployeeControl.Visibility           = Visibility.Collapsed;
            panelGoalLabel.Visibility                 = Visibility.Visible;
            panelGoalTree.Visibility                  = Visibility.Visible;

            SetEmployeeComboVisibility();
			SetRebookingButtonVisibility();

            if (chkWithClient != null)
            {
                chkWithClient.IsEnabled = true;
            }

            SelectedItemChanged(supportConceptSelectionControl.SelectedItem);
        }

        private void ChkWithClient_Checked(object sender, RoutedEventArgs e)
        {
            if (customerSelectAndInfoGrid != null)
            {
                customerSelectAndInfoGrid.Visibility = Visibility.Visible;
            }

            WithoutClient = false;

            if (supportConceptSelectionControl != null)
            {
                var selectedNode = supportConceptSelectionControl.SelectedItem;
                SelectedItemChanged(selectedNode);
            }

            if (chkGroupBooking != null)
            {
                chkGroupBooking.IsEnabled = true;
            }

            if (chkMultiBooking != null)
            {
                chkMultiBooking.IsEnabled = true;
            }

			SetRebookingButtonVisibility();
        }

        private void ChkWithClient_Unchecked(object sender, RoutedEventArgs e)
        {
            if (customerSelectAndInfoGrid != null)
            {
                customerSelectAndInfoGrid.Visibility = Visibility.Collapsed;
            }

            WithoutClient = true;

            SelectedItemChanged(null);

            if (chkGroupBooking != null)
            {
                chkGroupBooking.IsEnabled = false;
            }

            if (chkMultiBooking != null)
            {
                chkMultiBooking.IsEnabled = false;
            }

			SetRebookingButtonVisibility();
        }

        private void ChkWohnheimBookingChecked(object sender, RoutedEventArgs e)
        {
            chkWithClient.IsEnabled   = false;
            chkMultiBooking.IsEnabled = false;
            chkGroupBooking.IsEnabled = false;

            WithoutClient = true;
            SelectedItemChanged(null);

            customerDetailGrid.Visibility        = Visibility.Collapsed;
            zeitraumGrid.Visibility              = Visibility.Collapsed;
            customerSelectAndInfoGrid.Visibility = Visibility.Collapsed;
            wohnheimbuchungsGrid.Visibility      = Visibility.Visible;
            btnSaveWohnheimbuchung.Visibility    = Visibility.Visible;

            UpdateWohnheimBuchungGrid();
            PreselectSupportConceptsFromWohnheim(ViewModel.SelectedWohnheimbuchung.Wohnheim);
        }

        private void UpdateWohnheimBuchungGrid()
        {
            LoadExistingWohnheimbuchung(foundExistingBuchung => this.Dispatch(() =>
            {
                BeWoWpfUtils.RefreshDXGrid(SupportConcept2WohnheimbuchungGridControl);
                BeWoWpfUtils.RefreshDXGrid(Employee2WohnheimbuchungGridControl);

                if (!foundExistingBuchung)
                {
                    return;
                }

                var firstDate = ViewModel.SelectedWohnheimbuchung.Buchungsdatum.Value;

                foreach (var item in ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.VMList.Where(w => w.StartDate != null && w.EndDate != null))
                {
                    item.StartDate = firstDate.MergeDatesByDate(item.StartDate.Value);
                    item.EndDate = firstDate.MergeDatesByDate(item.EndDate.Value);
                }

                foreach (var item in ViewModel.SelectedWohnheimbuchung.EmployeeList.VMList.Where(w => w.StartDate != null && w.EndDate != null))
                {
                    item.StartDate = firstDate.MergeDatesByDate(item.StartDate.Value);
                    item.EndDate = firstDate.MergeDatesByDate(item.EndDate.Value);
                }
            }));
        }

        private void ChkWohnheimBookingUnchecked(object sender, RoutedEventArgs e)
        {
            chkWithClient.IsEnabled   = true;
            chkMultiBooking.IsEnabled = true;
            chkGroupBooking.IsEnabled = true;

            WithoutClient = false;

            if (supportConceptSelectionControl != null)
            {
                var selectedNode = supportConceptSelectionControl.SelectedItem;
                SelectedItemChanged(selectedNode);
            }

            customerDetailGrid.Visibility        = Visibility.Visible;
            zeitraumGrid.Visibility              = Visibility.Visible;
            customerSelectAndInfoGrid.Visibility = Visibility.Visible;
            wohnheimbuchungsGrid.Visibility      = Visibility.Collapsed;
            btnSaveWohnheimbuchung.Visibility    = Visibility.Collapsed;
        }

        private void SupportConceptSelectionControl_ItemSelected(object sender, EventArgs<FlatSupportConceptTreeNodeDC> e)
        {
            if (chkGroupBooking.IsChecked.Value || chkMultiBooking.IsChecked.Value)
            {
                return;
            }

            var selectedNode = e.Data;
            SelectedItemChanged(selectedNode);

            ComboBoxTreeViewControl.ResetControl();

            foreach (var item in ViewModel.PrototypeVM.GoalTree)
            {
                item.IsChecked = false;
            }

            ComboBoxTreeViewControl.TreeViewSourceList = ViewModel.PrototypeVM.GoalTree;
        }

        private void LinkExcelExportRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            var list = srListBox.ItemsSource as List<ServiceRecordVM>;

            var lHeaderCaptions = new List<string>();
            var lContent = new List<List<string>>();

	        if (BeWoApp.AppSettings.IsEndDateVisible)
	        {
				lHeaderCaptions.Add("Startdatum");
				lHeaderCaptions.Add("Enddatum");
	        }
	        else
	        {
				lHeaderCaptions.Add("Datum");
	        }
            
			lHeaderCaptions.Add("Von");
			lHeaderCaptions.Add("Bis");
            lHeaderCaptions.Add("FLM");
            lHeaderCaptions.Add("FLM gerundet");
            lHeaderCaptions.Add("Mitarbeiter");
            lHeaderCaptions.Add("Klient");
            lHeaderCaptions.Add("Hilfeplan");
            lHeaderCaptions.Add("Kostenträger");
            lHeaderCaptions.Add("Kategorie");
            lHeaderCaptions.Add("Leistung");
	        if (ViewModel.AllDocTypes != null && ViewModel.AllDocTypes.Count > 0)
	        {
		        foreach (var dt in ViewModel.AllDocTypes)
		        {
					lHeaderCaptions.Add(dt.TypeDescription);
		        }
	        }
	        else
	        {
				lHeaderCaptions.Add("Dokumentation");
	        }
            
            lHeaderCaptions.Add("Ziele");

            if (list != null)
            {
	            foreach (var vm in list)
	            {
					var row = new List<string>();

					if (BeWoApp.AppSettings.IsEndDateVisible)
					{
						row.Add(String.Format("{0:dd.MM.yyyy}", vm.StartTime));
						row.Add(String.Format("{0:dd.MM.yyyy}", vm.EndDate));
					}
					else
					{
						row.Add(String.Format("{0:dd.MM.yyyy}", vm.Date));
					}

					row.Add(String.Format("{0:HH:mm}", vm.StartTime != null && vm.StartTime.Value.Second == 0 ? vm.StartTime : null));
					row.Add(String.Format("{0:HH:mm}", vm.EndTime != null && vm.EndTime.Value.Second == 0 ? vm.EndTime : null));
					row.Add(vm.AssistanceDuration.ToString());
					row.Add(vm.RoundedDuration.ToString());
					row.Add(vm.Employee != null ? vm.Employee.ToString() : string.Empty);
					row.Add(vm.Customer != null ? vm.Customer.ToString() : string.Empty);
					row.Add(vm.SupportConcept != null ? vm.SupportConcept.ToString() : string.Empty);
					row.Add(vm.CostBearer != null ? vm.CostBearer.ToString() : string.Empty);
					row.Add(vm.Category != null ? vm.Category.ToString() : string.Empty);
					row.Add(vm.ServiceDescription != null ? vm.ServiceDescription.ToString() : string.Empty);

					row.Add(vm.Notice);
					if (ViewModel.AllDocTypes != null)
					{
						if (ViewModel.AllDocTypes.Count == 2)
						{
							row.Add(vm.Notice2);
						}
						if (ViewModel.AllDocTypes.Count == 3)
						{
							row.Add(vm.Notice3);
						}
						if (ViewModel.AllDocTypes.Count == 4)
						{
							row.Add(vm.Notice4);
						}
						if (ViewModel.AllDocTypes.Count == 5)
						{
							row.Add(vm.Notice5);
						}
					}
					
					row.Add(vm.GoalString);

					//lContent.AddRange(list.Select(vm => new List<string>
					//									{
					//										String.Format("{0:dd.MM.yyyy}", vm.StartTime != null ? vm.Date : null), 
					//										String.Format("{0:HH:mm}", vm.StartTime != null && vm.StartTime.Value.Second == 0 ? vm.StartTime : null), 
					//										String.Format("{0:HH:mm}", vm.EndTime != null && vm.EndTime.Value.Second == 0 ? vm.EndTime : null), 
					//										vm.AssistanceDuration.ToString(), 
					//										vm.RoundedDuration.ToString(), 
					//										vm.Employee != null ? vm.Employee.ToString() : string.Empty, 
					//										vm.Customer != null ? vm.Customer.ToString() : string.Empty, 
					//										vm.SupportConcept != null ? vm.SupportConcept.ToString() : string.Empty, 
					//										vm.CostBearer != null ? vm.CostBearer.ToString() : string.Empty, 
					//										vm.Category != null ? vm.Category.ToString() : string.Empty, 
					//										vm.ServiceDescription != null ? vm.ServiceDescription.ToString() : string.Empty, 
					//										vm.Notice,vm.Notice2,vm.Notice3,vm.Notice4,vm.Notice5, 
					//										vm.GoalString
					//									}));
					lContent.Add(row);
	            }
               
            }

			var path = BeWoApp.GetAndCreateUserAppDataPath() + "\\Dokumentation.xls";

            var sf = new SaveFileDialog { FileName = Path.GetFileName(path), Filter = "Microsoft Excel 97-2003-Arbeitsblatt|*.xls|Alle Dateien|*.*" };
            if (sf.ShowDialog() != true)
                return;
            ServiceFacade.DoDownloadServiceSync(s => BeWoUtils.WriteExcelFile(s.PrepareExcelFile(DownloadLinkEngine.ExcelFileId, lHeaderCaptions, lContent), sf.FileName));
        }

        private void MultiSupportConceptControl_ItemSelected(object sender, EventArgs<CompactSupportConceptDC> e)
        {
            FlatSupportConceptTreeNodeDC flatNode = SupportConceptService.CreateFlatSupportConceptItem(e.Data, null);

            SelectedItemChanged(flatNode);
        }

        private void PopupeditEmployeePopUpClick(object sender, RoutedEventArgs e)
        {
            popup_employee.IsOpen = true;
        }

        private void UpdateAssessmentSheet(FlatSupportConceptTreeNodeDC selectedNode)
        {
            if (assessmentSheet == null) 
                return;

            if (selectedNode != null && selectedNode.SupportConceptTreeNodeDC != null)
            {
                var customer = selectedNode.SupportConceptTreeNodeDC.Customer;
                if (customer != null)
                {
                    if (!customerContainsAssessmentCategories.ContainsKey(customer))
                    {
                        ServiceFacade.DoCustomerServiceAsync(
                            s1 => s1.LoadCustomerAssessmentSheetCategoryList(customer.Oid.Value),

                            cb => this.Dispatch(
                                delegate
                                    {
                                        customerContainsAssessmentCategories.Add(customer, cb);

                                        UpdateAssessmentSheet(selectedNode.SupportConceptTreeNodeDC.Customer, cb);
                                    }), false);
                    }
                    else
                    {
                        var cats = customerContainsAssessmentCategories[customer];
                        UpdateAssessmentSheet(selectedNode.SupportConceptTreeNodeDC.Customer, cats);
                    }
                }
            }
            else
            {
                HideAssessmentSheet();
            }
        }

        private DockLayoutManager dockLayoutManager;
        private LayoutPanel       layoutPanel1;
        private LayoutPanel       layoutPanel2;
        private LayoutPanel       layoutPanel3;
        private Grid              panel1;
        private Grid              panel2;
        private Grid              panel3;

        private void CreateLayoutManager()
        {
            dockLayoutManager = new DockLayoutManager();
            dockLayoutManager.SetValue(Grid.RowProperty, 2);
			dockLayoutManager.SetValue(Grid.ColumnSpanProperty, 2);
            dockLayoutManager.Margin = new Thickness(0, 5, 0, 0);
            dockLayoutManager.SetValue(ThemeManager.ThemeNameProperty, "LightGray");
            dockLayoutManager.Background = Brushes.Transparent;
            dockLayoutManager.Visibility = Visibility.Hidden;
            dockLayoutManager.ShowingDockHints += dockLayoutManager_ShowingDockHints;
            
            var group = new LayoutGroup();
            dockLayoutManager.LayoutRoot = group;

            layoutPanel1 = new LayoutPanel
                               {
                                   Caption = "Neue Leistung hinzufügen", 
                                   ItemWidth = GridLength.Auto, ShowCloseButton = false, 
                                   ShowPinButton = false, 
                                   AllowDrag = false, 
                                   AllowMove = false, 
                                   CaptionHorizontalAlignment = HorizontalAlignment.Stretch, 
                                   CaptionTemplate = (DataTemplate) FindResource("LayoutPanelCaptionTemplate")
                               };

            var border = new Border
                             {
                                 Background = new SolidColorBrush(Color.FromRgb(195, 203, 206)), 
                                 BorderThickness = new Thickness(0), 
                                 BorderBrush = Brushes.Gray
                             };

            panel1 = new Grid {Margin = new Thickness(4)};
            border.Child = panel1;

            layoutPanel1.Content = border;

            group.Items.Add(layoutPanel1);

            layoutPanel2 = new LayoutPanel
                               {
                                   Caption = "Leistungen", 
                                   ItemWidth = new GridLength(1, GridUnitType.Star), 
                                   ShowCloseButton = false, 
                                   ShowPinButton = false, 
                                   AllowDrag = false, 
                                   AllowMove = false, 
                                   CaptionTemplate = (DataTemplate) FindResource("LayoutPanelCaptionTemplate"), 
                                   CaptionHorizontalAlignment = HorizontalAlignment.Stretch
                               };

            border = new Border
                         {
                             Background = new SolidColorBrush(Color.FromRgb(195, 203, 206)), 
                             BorderThickness = new Thickness(0), 
                             BorderBrush = Brushes.Gray
                         };

            panel2 = new Grid {Margin = new Thickness(0)};
            border.Child = panel2;

            layoutPanel2.Content = border;

            group.Items.Add(layoutPanel2);

            layoutPanel3 = new LayoutPanel
                               {
                                   Caption = "Punktebogen", 
                                   ItemWidth = new GridLength(400, GridUnitType.Pixel), 
                                   ShowCloseButton = false, 
                                   ShowPinButton = false, 
                                   AllowDrag = false, 
                                   AllowMove = false, 
                                   CaptionTemplate = (DataTemplate) FindResource("LayoutPanelCaptionTemplate"), 
                                   CaptionHorizontalAlignment = HorizontalAlignment.Stretch
                               };

            border = new Border
                         {
                             Background = new SolidColorBrush(Color.FromRgb(195, 203, 206)), 
                             BorderThickness = new Thickness(0), 
                             BorderBrush = Brushes.Gray
                         };

            panel3 = new Grid {Margin = new Thickness(0, 4, 0, 0)};
            border.Child = panel3;

            layoutPanel3.Content = border;

            group.Items.Add(layoutPanel3);

            root.Children.Add(dockLayoutManager);

            InitDockPanel();

            assessmentSheet.LayoutManager = dockLayoutManager;
        }

        static void dockLayoutManager_ShowingDockHints(object sender, DevExpress.Xpf.Docking.Base.ShowingDockHintsEventArgs e)
        {
            e.DisableAll();
            e.HideAll();
            e.Handled = true;
        }

        private void HideAssessmentSheet()
        {
            assessmentSheet.SetCustomer(null, null);
            assessmentSheet.Visibility = Visibility.Collapsed;

            customerDetailGrid.Visibility = Visibility.Visible;
            
            if (dockLayoutManager != null)
                dockLayoutManager.Visibility = Visibility.Collapsed;

            if (customerDetailGrid.Children.Count != 0) 
                return;

            if (panel1 != null)
            {
                panel1.Children.Clear();
                panel2.Children.Clear();
                panel3.Children.Clear();
            }

            groupBoxNeueLeistung.Content = gridNeueLeistung;
            customerDetailGrid.Children.Add(groupBoxNeueLeistung);
            customerDetailGrid.Children.Add(serviceRecordListContent);
            customerDetailGrid.Children.Add(txtServiceListCount);
            customerDetailGrid.Children.Add(stackPanelInfoText);
            customerDetailGrid.Children.Add(punktebogenRootGrid);
        }

        private void ShowAssessmentSheet(CompactCustomerDC customer, List<AssessmentSheetCategoryDC> cats)
        {
            if (dockLayoutManager == null)
                CreateLayoutManager();
            
            assessmentSheet.SetCustomer(customer, cats);

            if (assessmentSheet.Visibility == Visibility.Visible) 
                return;

            assessmentSheet.Visibility = Visibility.Visible;

            customerDetailGrid.Visibility = Visibility.Collapsed;
            dockLayoutManager.Visibility = Visibility.Visible;

            if (customerDetailGrid.Children.Count > 0)
                customerDetailGrid.Children.Clear();

            groupBoxNeueLeistung.Content = null;
            panel1.Children.Add(gridNeueLeistung);
            panel2.Children.Add(serviceRecordListContent);
            panel2.Children.Add(txtServiceListCount);
            panel2.Children.Add(stackPanelInfoText);
            panel3.Children.Add(punktebogenRootGrid);
        }

        private void UpdateAssessmentSheet(CompactCustomerDC customer, List<AssessmentSheetCategoryDC> cats)
        {
            if (cats.Count == 0)
            {
                HideAssessmentSheet();
            }
            else
            {
                ShowAssessmentSheet(customer, cats);
            }
        }

        private BaseLayoutItem lastPanel;
        private LayoutGroup    lastParentGroup;
        private LayoutPanel    emptyPanel;
        private int            lastIndexWithinParent;
        private int            lastIndexWithinRoot;
        
        private void InitDockPanel()
        {
            if (assessmentSheet == null)
            {
                return;
            }

            foreach (var item in dockLayoutManager.LayoutRoot.GetItems())
            {
                var layoutGroup = item as LayoutGroup;
                if (layoutGroup != null)
                {
                    foreach (LayoutPanel layoutPanel in (layoutGroup).Items)
                    {
                        AddMaximizeRestoreButtons(layoutPanel);
                    }
                }
                else if (item is LayoutPanel)
                {
                    AddMaximizeRestoreButtons(item as LayoutPanel);
                }
            }

            foreach (var layoutPanel in dockLayoutManager.FloatGroups.SelectMany(floatGroup => floatGroup.Items.Cast<LayoutPanel>()))
            {
                AddMaximizeRestoreButtons(layoutPanel);
            }
        }

        private Rect CalcMaximizedBounds(Rect restoreBounds)
        {
            var bounds = WindowHelper.GetMaximizeBounds(dockLayoutManager, restoreBounds);
            bounds.Inflate(new Size(5, 5));
            return bounds;
        }

        private void ButtonClickHandler(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            var item = DockLayoutManager.GetLayoutItem(sender as DependencyObject);

            if (btn.Content.ToString() == "Maximieren")
            {
                item.CaptionTemplate = (DataTemplate)FindResource("LayoutPanelCaptionTemplateMinimize");

                //btn.Content = "Wiederherstellen";
                //btn.ToolTip = btn.Content;
                //btn.Style = (Style) FindResource("DockPanelRestoreButtonStyle");
                
                MaximizeButtonClickHandler(item);
                
                if (Equals(item, layoutPanel1))
                {
                    popupedit_employee.Focus();
                }
                else if (Equals(item, layoutPanel2))
                {
                    srListBox.Focus();
                }
                else if (Equals(item, layoutPanel3))
                {
                    assessmentSheet.Focus();
                }
            } 
            else
            {
                item.CaptionTemplate = (DataTemplate)FindResource("LayoutPanelCaptionTemplate");

                //btn.Content = "Maximieren";
                //btn.ToolTip = btn.Content;
                //btn.Style = (Style)this.FindResource("DockPanelMaximizeButtonStyle");
                RestoreButtonClickHandler(item);
            }
        }

        private void MaximizeButtonClickHandler(BaseLayoutItem item)
        {
            //BaseLayoutItem item = DockLayoutManager.GetLayoutItem(sender as DependencyObject);
            if (item == null || item.GetRoot() == null) return;

            lastParentGroup = item.Parent;
            lastPanel = item;

            if (item.GetRoot() is FloatGroup)
            {
                MaximizeFloatButtonClickHandler(item);
            }
            else
            {
                MaximizeDockButtonClickHandler(item);
            }

            if (!(item.ControlBoxContent is StackPanel)) return;
            var controlBox = item.ControlBoxContent as StackPanel;
            foreach (var child in controlBox.Children)
            {
                if (child is Button && ((Button)child).Content.ToString() == "Maximieren")
                {
                    ((Button)child).Visibility = Visibility.Collapsed;
                }
                else if (child is Button && ((Button)child).Content.ToString() == "Wiederherstellen")
                {
                    ((Button)child).Visibility = Visibility.Visible;
                }
            }
        }

        private void RestoreButtonClickHandler(BaseLayoutItem item)
        {
            //BaseLayoutItem item = DockLayoutManager.GetLayoutItem(sender as DependencyObject);
            if (item == null)
            {
                return;
            }

            if (lastParentGroup is FloatGroup)
            {
                RestoreFloatButtonClickHandler(item);
            }
            else
            {
                RestoreDockButtonClickHandler(item);
            }

            if (!(item.ControlBoxContent is StackPanel))
            {
                return;
            }

            var controlBox = item.ControlBoxContent as StackPanel;

            foreach (var child in controlBox.Children)
            {
                if (child is Button && ((Button)child).Content.ToString() == "Maximieren")
                {
                    ((Button)child).Visibility = Visibility.Visible;
                }
                else if (child is Button && ((Button)child).Content.ToString() == "Wiederherstellen")
                {
                    ((Button)child).Visibility = Visibility.Collapsed;
                }
            }
        }

        private void MaximizeFloatButtonClickHandler(BaseLayoutItem item)
        {
            //BaseLayoutItem item = DockLayoutManager.GetLayoutItem(sender);
            if (item == null || !(item.GetRoot() is FloatGroup))
            {
                return;
            }

            var parent        = item.GetRoot() as FloatGroup;
            var restoreBounds = new Rect(parent.FloatLocation, parent.FloatSize);
            var bounds        = CalcMaximizedBounds(restoreBounds);

            DocumentPanel.SetRestoreBounds(parent, restoreBounds);

            parent.FloatLocation = new Point(bounds.X, bounds.Y);
            parent.FloatSize     = new Size(bounds.Width, bounds.Height);
        }

        private static void RestoreFloatButtonClickHandler(BaseLayoutItem item)
        {
            //BaseLayoutItem item = DockLayoutManager.GetLayoutItem(sender);
            if (item == null || !(item.GetRoot() is FloatGroup))
            {
                return;
            }

            var parent = item.GetRoot() as FloatGroup;
            var bounds = DocumentPanel.GetRestoreBounds(parent);

            parent.FloatLocation = new Point(bounds.X, bounds.Y);
            parent.FloatSize     = new Size(bounds.Width, bounds.Height);
        }

        private void MaximizeDockButtonClickHandler(BaseLayoutItem item)
        {
            //BaseLayoutItem item = DockLayoutManager.GetLayoutItem(sender);
            if (item == null || item.GetRoot() == null)
            {
                return;
            }

            if (lastParentGroup is TabbedGroup)
            {
                lastIndexWithinParent = lastParentGroup.Items.IndexOf(item);
                emptyPanel            = new LayoutPanel();

                dockLayoutManager.DockController.Insert(lastParentGroup, emptyPanel, lastParentGroup.Items.Count);
            }
            else
            {
                lastIndexWithinRoot = dockLayoutManager.LayoutRoot.Items.IndexOf(lastParentGroup);

                if (lastIndexWithinRoot == -1)
                {
                    lastIndexWithinRoot = dockLayoutManager.LayoutRoot.Items.IndexOf(lastPanel);
                }
            }

            var parent = dockLayoutManager.DockController.Float(item);
            //parent.Items[0].Focus();
            //parent.ItemsAppearance.Active.Background = Brushes.Transparent;
            //LayoutPanel lp = item as LayoutPanel;
            //if (lp != null)
            //    lp.Background = Brushes.Transparent;

            var width  = dockLayoutManager.ActualWidth + 5;
            var height = dockLayoutManager.ActualHeight + 5;
            var pos    = new Point(-5, -5);

            var restoreBounds = new Rect(pos, new Point(width, height));
            var bounds        = CalcMaximizedBounds(restoreBounds);

            DocumentPanel.SetRestoreBounds(parent, restoreBounds);

            parent.FloatLocation = new Point(restoreBounds.X, restoreBounds.Y);
            parent.FloatSize     = new Size(restoreBounds.Width, restoreBounds.Height);

        }

        private void RestoreDockButtonClickHandler(BaseLayoutItem item)
        {
            //BaseLayoutItem item = DockLayoutManager.GetLayoutItem(sender);
            if (item == null)
            {
                return;
            }

            if (lastParentGroup is TabbedGroup)
            {
                dockLayoutManager.DockController.Insert(lastParentGroup, item, lastIndexWithinParent);
                dockLayoutManager.DockController.RemovePanel(emptyPanel);
                dockLayoutManager.DockController.Activate(item);

                emptyPanel            = null;
                lastIndexWithinParent = -1;

                return;
            }

            //this.lastParentGroup.Items.Add(item);
            dockLayoutManager.DockController.Insert(dockLayoutManager.LayoutRoot, lastPanel, lastIndexWithinRoot);
            lastIndexWithinRoot = -1;
        }

        private static void AddMaximizeRestoreButtons(LayoutPanel layoutPanel)
        {
            //StackPanel stackPanel = new StackPanel { Orientation = Orientation.Horizontal };

            //Button maximizeButton = new Button();
            //maximizeButton.Content = "Maximieren";
            //maximizeButton.ToolTip = "Maximieren";
            //maximizeButton.Click += this.MaximizeButtonClickHandler;
            //maximizeButton.Style = (Style)this.FindResource("DockPanelMaximizeButtonStyle");

            //Button restoreButton = new Button();
            //restoreButton.Content = "Wiederherstellen";
            //restoreButton.ToolTip = "Wiederherstellen";
            //restoreButton.Click += this.RestoreButtonClickHandler;
            //restoreButton.MouseDown += new MouseButtonEventHandler(restoreButton_MouseDown);
            //restoreButton.Style = (Style)this.FindResource("DockPanelRestoreButtonStyle");
            //restoreButton.Visibility = Visibility.Collapsed;

            //stackPanel.Children.Add(maximizeButton);
            //stackPanel.Children.Add(restoreButton);

            //layoutPanel.ControlBoxContent = stackPanel;
        }

        private void ChkRowView_Checked(object sender, RoutedEventArgs e)
        {
            if (srListBox == null) 
                return;

            srListBox.Visibility = Visibility.Visible;
            //###Bars
            srGridControl.Visibility = Visibility.Hidden;

            BeWoApp.AppSettings.ShowServiceRecordGridControl = false;
            BeWoApp.SaveAppSettings();
        }

        private void ChkDetailView_Checked(object sender, RoutedEventArgs e)
        {
            if (srListBox == null)
                return;

            srListBox.Visibility = Visibility.Hidden;

            //###Bars
            srGridControl.Visibility = Visibility.Visible;
            object ds = srGridControl.ItemsSource;
            object selected = srTableView.FocusedRow;
            srGridControl.ItemsSource = null;
            srGridControl.ItemsSource = ds;
            srTableView.FocusedRow = selected;

            BeWoApp.AppSettings.ShowServiceRecordGridControl = true;
            BeWoApp.SaveAppSettings();
        }

        private void SrTableView_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //###Bars
            var hitInfo = srTableView.CalcHitInfo(e.OriginalSource as DependencyObject);
            if (!hitInfo.InRow) 
                return;

            ServiceRecordVM vm = GetSelectedServiceRecordFromGrid();
            if (vm != null && vm.EditAllowed)
                StartEdit(vm);
        }

        private ServiceRecordVM GetSelectedServiceRecordFromGrid()
        {
            //###Bars
            var selected = srTableView.SelectedRows;
            if (selected != null && selected.Count > 0)
                return selected[0] as ServiceRecordVM;
            return null;
        }

        private void DxEditButton_OnItemClick(object sender, ItemClickEventArgs e)
        {
            ServiceRecordVM vm = GetSelectedServiceRecordFromGrid();

	        if (vm != null)
	        {
		        if (vm.EditAllowed)
			        StartEdit(vm);
	        }
        }

        private void DxDeleteButton_OnItemClick(object sender, ItemClickEventArgs e)
        {
            ServiceRecordVM vm = GetSelectedServiceRecordFromGrid();
            if (vm != null && vm.DeleteAllowed)
                Delete(vm);
        }

		private void DxHistoryButton_OnItemClick(object sender, ItemClickEventArgs e)
        {
            ServiceRecordVM vm = GetSelectedServiceRecordFromGrid();
            if (vm != null && ServiceRecordVM.IsHistoryAllowed)
				ShowHistory(vm);
        }
		
        public override void ModalPopUpCloseInvoked()
        {
            MainControl.CloseCurrentPopUp();
        }

        public override void ModalPopUpSaveInvoked()
        {
            if (_GroupOfPeopleModalPopUp != null)
                _GroupOfPeopleModalPopUp.SaveData();       
        }

        void multiSupportConceptControl_EditGroupButtonClicked(object sender, EventArgs e)
        {
            OpenGroupEditView();
        }
        
        private void OpenGroupEditView()
        {
            VMFactory.CreateGroupOfPeopleListVMAsync(
               cb => this.Dispatch(
                   delegate
                   {
                       if (cb.VMList.Count > 0)
                           cb.EditVM = cb.VMList[0];

                       _GroupOfPeopleModalPopUp = new GroupOfPeopleView(cb) {MinWidth = 900, MaxWidth = 900, Height = 600};
                       _GroupOfPeopleModalPopUp.CommandBindings.Add(
                           new CommandBinding(
                               ApplicationCommands.Close,
                               (s, e) =>
                                   {
                                       if (_GroupOfPeopleModalPopUp.DoSaveCheck())
                                           BeWoApp.MainControl.CloseCurrentPopUp();
                                   }));
                       _GroupOfPeopleModalPopUp.GroupOfPeopleSavedOrUpdated += GroupOfPeopleModalPopUp_GroupOfPeopleSavedOrUpdated;
                       BeWoApp.MainControl.ShowControlAsModalPopUp(_GroupOfPeopleModalPopUp);
                       _GroupOfPeopleModalPopUp.Focus();
                   }));
        }

        private static void GroupOfPeopleModalPopUp_GroupOfPeopleSavedOrUpdated(object sender, EventArgs<GroupOfPeopleListVM> e)
        {
            //ServiceFacade.DoCustomerServiceAsync(
            //    s => s.LoadPersonCompact(e.Data.DataContract.PersonOid.Value),
            //    p => this.Dispatch(
            //        delegate
            //        {
            BeWoApp.MainControl.CloseCurrentPopUp();
            //        }));
        }

        private void LinkPdfExport_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
			if ((chkGroupBooking.IsChecked == null || chkGroupBooking.IsChecked != null && chkGroupBooking.IsChecked.Value) || 
				(chkMultiBooking.IsChecked == null || chkMultiBooking.IsChecked != null && chkMultiBooking.IsChecked.Value))
	        {
		        return;
	        }

			long scOid = 0;
			long cOid = 0;
			long cb2scOid = 0;
			var eOid = BeWoApp.LoggedOnUser.Employee.EmployeeOid;

	        var selectedNode = ViewModel.SelectedCustomerNode;

			if (selectedNode != null && selectedNode.SupportConceptTreeNodeDC != null)
			{
				if (selectedNode.SupportConceptTreeNodeDC.SupportConcept != null)
					scOid = selectedNode.SupportConceptTreeNodeDC.SupportConcept.SupportConceptOid;

				if (selectedNode.SupportConceptTreeNodeDC.Customer != null)
					cOid = selectedNode.SupportConceptTreeNodeDC.Customer.CustomerOid;

				if (selectedNode.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC != null)
					cb2scOid = selectedNode.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC.CostBearer2SupportConceptOid.Value;
			}
			else
			{
				if (_SelectedEmployee != null)
				{
					eOid = _SelectedEmployee.EmployeeOid;
				}
			}

	        var sr = ViewModel.ServiceRecordsForSelectedCustomer;

	        var earliestStartDate = sr.Any() ? sr.OrderBy(o => o.StartDate).First().StartDate.Value : DateTime.Now;
	        var latestEndDate     = sr.Any() ? sr.OrderByDescending(o => o.EndDate).First().EndDate.Value : DateTime.Now.AddSeconds(1);

	        if (latestEndDate.Hour == 0 && latestEndDate.Minute == 0 && latestEndDate.Second == 1)
	        {
				latestEndDate = latestEndDate.AddHours(23);
				latestEndDate = latestEndDate.AddMinutes(59);
	        }

	        ServiceFacade.DoReportServiceAsync(s => s.CreateServiceRecordListReport(eOid, cOid, scOid, cb2scOid, false, new DateTimeSpan { StartDate = earliestStartDate, StartHours = earliestStartDate.Hour, StartMinutes = earliestStartDate.Minute, EndDate = latestEndDate, EndHours = latestEndDate.Hour, EndMinutes = latestEndDate.Minute }),
											   cb => this.Dispatch(() => BeWoUtils.ShowReportWindow(cb, null, "Dokumentation")));
        }

        private void PopupInfo_OnOpened(object sender, EventArgs e)
        {
            ServiceRecordVM vm = GetSelectedServiceRecordFromGrid();

	        if (vm != null)
	        {
		        dxEditButton.IsEnabled = vm.EditAllowed;
		        dxDeleteButton.IsEnabled = vm.DeleteAllowed;
		        dxHistoryButton.IsVisible = ServiceRecordVM.IsHistoryAllowed;
	        }
        }

        private void Popupedit_employee_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                return;
            }

            var employeeCompact = ViewModel.SelectedEmployee ?? BeWoApp.LoggedOnUser.Employee;

            VMFactory.CreateEmployeeVMAsync(employeeCompact.EmployeeOid,
                cb => this.Dispatch(
                    () => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, ServiceRecordView2>(cb, this, () => this.Dispatch(
                    () => BeWoUtils.UpdateAllViews(employeeCompact)))));
        }

        private void ReloadButton_OnClick(object sender, RoutedEventArgs e)
        {
            ViewModel.BuildServiceRecordsForSelectedTreeNode(true);
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            popup_textbausteine.IsOpen = true;
        }

        private void TextbausteineSearchView_OnItemSelected(object sender, EventArgs<TextbausteinDC> e)
        {
            if (TabItem1_Notice.IsSelected)
            {
                    
                    var caretIndex = dokumentationsTextBox.CaretIndex;

                    if (string.IsNullOrEmpty(dokumentationsTextBox.Text))
                    {
                        dokumentationsTextBox.Text = e.Data.Text;
                        dokumentationsTextBox.CaretIndex = dokumentationsTextBox.Text.Length;
                    }
                    else
                    {
                        if (dokumentationsTextBox.CaretIndex == 0)
                        {
                            dokumentationsTextBox.Text = e.Data.Text + dokumentationsTextBox.Text;
                        }
                        else if (dokumentationsTextBox.CaretIndex == dokumentationsTextBox.Text.Length)
                        {
                            dokumentationsTextBox.Text = dokumentationsTextBox.Text + e.Data.Text;
                        }
                        else
                        {
                            var anzahlLeerzeichen = dokumentationsTextBox.CaretIndex - dokumentationsTextBox.Text.Length;

                            var leerzeichen = String.Empty;
                            for (var i = 0; i < anzahlLeerzeichen; i++)
                            {
                                leerzeichen += " ";
                            }

                            var start = dokumentationsTextBox.Text.Substring(0, (dokumentationsTextBox.CaretIndex - anzahlLeerzeichen));
                            var ende = dokumentationsTextBox.Text.Substring((dokumentationsTextBox.CaretIndex - anzahlLeerzeichen));

                            dokumentationsTextBox.Text = start + leerzeichen + e.Data.Text + ende;
                        }

                        dokumentationsTextBox.CaretIndex = caretIndex + e.Data.Text.Length;

                        popup_textbausteine.IsOpen = false;

                        if (grosseDokuTextBox == null)
                        {
                            dokumentationsTextBox.Focus();
                        }
                        else
                        {
                            grosseDokuTextBox.Text = dokumentationsTextBox.Text;
                        }
                    }
                }else
                if (TabItem2_Notice.IsSelected)
                {
                    var caretIndex = dokumentationsTextBox2.CaretIndex;

                    if (string.IsNullOrEmpty(dokumentationsTextBox2.Text))
                    {
                        dokumentationsTextBox2.Text = e.Data.Text;
                        dokumentationsTextBox2.CaretIndex = dokumentationsTextBox2.Text.Length;
                    }
                    else
                    {
                        if (dokumentationsTextBox2.CaretIndex == 0)
                        {
                            dokumentationsTextBox2.Text = e.Data.Text + dokumentationsTextBox2.Text;
                        }
                        else if (dokumentationsTextBox2.CaretIndex == dokumentationsTextBox2.Text.Length)
                        {
                            dokumentationsTextBox2.Text = dokumentationsTextBox2.Text + e.Data.Text;
                        }
                        else
                        {
                            var anzahlLeerzeichen = dokumentationsTextBox2.CaretIndex - dokumentationsTextBox2.Text.Length;

                            var leerzeichen = String.Empty;
                            for (var i = 0; i < anzahlLeerzeichen; i++)
                            {
                                leerzeichen += " ";
                            }

                            var start = dokumentationsTextBox2.Text.Substring(0, (dokumentationsTextBox2.CaretIndex - anzahlLeerzeichen));
                            var ende = dokumentationsTextBox2.Text.Substring((dokumentationsTextBox2.CaretIndex - anzahlLeerzeichen));

                            dokumentationsTextBox2.Text = start + leerzeichen + e.Data.Text + ende;
                        }

                        dokumentationsTextBox2.CaretIndex = caretIndex + e.Data.Text.Length;

                        popup_textbausteine.IsOpen = false;

                        if (grosseDokuTextBox == null)
                        {
                            dokumentationsTextBox2.Focus(); 
                        }
                        else
                        {
                            grosseDokuTextBox.Text = dokumentationsTextBox2.Text;
                        }
                    }
                }else
                 if (TabItem3_Notice.IsSelected)
                {
                    var caretIndex = dokumentationsTextBox3.CaretIndex;

                    if (string.IsNullOrEmpty(dokumentationsTextBox3.Text))
                    {
                        dokumentationsTextBox3.Text = e.Data.Text;
                        dokumentationsTextBox3.CaretIndex = dokumentationsTextBox3.Text.Length;
                    }
                    else
                    {
                        if (dokumentationsTextBox3.CaretIndex == 0)
                        {
                            dokumentationsTextBox3.Text = e.Data.Text + dokumentationsTextBox3.Text;
                        }
                        else if (dokumentationsTextBox3.CaretIndex == dokumentationsTextBox3.Text.Length)
                        {
                            dokumentationsTextBox3.Text = dokumentationsTextBox3.Text + e.Data.Text;
                        }
                        else
                        {
                            var anzahlLeerzeichen = dokumentationsTextBox3.CaretIndex - dokumentationsTextBox3.Text.Length;

                            var leerzeichen = String.Empty;
                            for (var i = 0; i < anzahlLeerzeichen; i++)
                            {
                                leerzeichen += " ";
                            }

                            var start = dokumentationsTextBox3.Text.Substring(0, (dokumentationsTextBox3.CaretIndex - anzahlLeerzeichen));
                            var ende = dokumentationsTextBox3.Text.Substring((dokumentationsTextBox3.CaretIndex - anzahlLeerzeichen));

                            dokumentationsTextBox3.Text = start + leerzeichen + e.Data.Text + ende;
                        }

                        dokumentationsTextBox3.CaretIndex = caretIndex + e.Data.Text.Length;

                        popup_textbausteine.IsOpen = false;

                        if (grosseDokuTextBox == null)
                        {
                            dokumentationsTextBox3.Focus();
                        }
                        else
                        {
                            grosseDokuTextBox.Text = dokumentationsTextBox3.Text;
                        }
                    }
                }else
                    if (TabItem4_Notice.IsSelected)
                {
                    var caretIndex = dokumentationsTextBox4.CaretIndex;

                    if (string.IsNullOrEmpty(dokumentationsTextBox4.Text))
                    {
                        dokumentationsTextBox4.Text = e.Data.Text;
                        dokumentationsTextBox4.CaretIndex = dokumentationsTextBox4.Text.Length;
                    }
                    else
                    {
                        if (dokumentationsTextBox4.CaretIndex == 0)
                        {
                            dokumentationsTextBox4.Text = e.Data.Text + dokumentationsTextBox4.Text;
                        }
                        else if (dokumentationsTextBox4.CaretIndex == dokumentationsTextBox4.Text.Length)
                        {
                            dokumentationsTextBox4.Text = dokumentationsTextBox4.Text + e.Data.Text;
                        }
                        else
                        {
                            var anzahlLeerzeichen = dokumentationsTextBox4.CaretIndex - dokumentationsTextBox4.Text.Length;

                            var leerzeichen = String.Empty;
                            for (var i = 0; i < anzahlLeerzeichen; i++)
                            {
                                leerzeichen += " ";
                            }

                            var start = dokumentationsTextBox4.Text.Substring(0, (dokumentationsTextBox4.CaretIndex - anzahlLeerzeichen));
                            var ende = dokumentationsTextBox4.Text.Substring((dokumentationsTextBox4.CaretIndex - anzahlLeerzeichen));

                            dokumentationsTextBox4.Text = start + leerzeichen + e.Data.Text + ende;
                        }

                        dokumentationsTextBox4.CaretIndex = caretIndex + e.Data.Text.Length;

                        popup_textbausteine.IsOpen = false;

                        if (grosseDokuTextBox == null)
                        {
                            dokumentationsTextBox4.Focus();
                        }
                        else
                        {
                            grosseDokuTextBox.Text = dokumentationsTextBox4.Text;
                        }
                    }
                }else
                if (TabItem5_Notice.IsSelected)
                {
                    var caretIndex = dokumentationsTextBox5.CaretIndex;

                    if (string.IsNullOrEmpty(dokumentationsTextBox5.Text))
                    {
                        dokumentationsTextBox5.Text = e.Data.Text;
                        dokumentationsTextBox5.CaretIndex = dokumentationsTextBox5.Text.Length;
                    }
                    else
                    {
                        if (dokumentationsTextBox5.CaretIndex == 0)
                        {
                            dokumentationsTextBox5.Text = e.Data.Text + dokumentationsTextBox5.Text;
                        }
                        else if (dokumentationsTextBox5.CaretIndex == dokumentationsTextBox5.Text.Length)
                        {
                            dokumentationsTextBox5.Text = dokumentationsTextBox5.Text + e.Data.Text;
                        }
                        else
                        {
                            var anzahlLeerzeichen = dokumentationsTextBox5.CaretIndex - dokumentationsTextBox5.Text.Length;

                            var leerzeichen = String.Empty;
                            for (var i = 0; i < anzahlLeerzeichen; i++)
                            {
                                leerzeichen += " ";
                            }

                            var start = dokumentationsTextBox5.Text.Substring(0, (dokumentationsTextBox5.CaretIndex - anzahlLeerzeichen));
                            var ende = dokumentationsTextBox5.Text.Substring((dokumentationsTextBox5.CaretIndex - anzahlLeerzeichen));

                            dokumentationsTextBox5.Text = start + leerzeichen + e.Data.Text + ende;
                        }

                        dokumentationsTextBox5.CaretIndex = caretIndex + e.Data.Text.Length;

                        popup_textbausteine.IsOpen = false;

                        if (grosseDokuTextBox == null)
                        {
                            dokumentationsTextBox5.Focus();
                        }
                        else
                        {
                            grosseDokuTextBox.Text = dokumentationsTextBox5.Text;
                        }
                    }
	            }
        }

        private void Combobox_category_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var serviceCategoryComboBox = (ComboBox) sender;
            if(serviceCategoryComboBox != null)
            {
                var category = (ServiceCategoryDC) serviceCategoryComboBox.SelectedItem;
                if (category != null && category.ServiceCategoryOid.HasValue)
                {
                    textbausteineSearchView.ServiceCategoryOid = category.ServiceCategoryOid.Value;
                }
            }
        }

        private void EditTextbausteineClick(object sender, RoutedEventArgs e)
        {
            VMFactory.CreateTextbausteinListVMAsync(
                x => this.Dispatch(delegate
                {
                    var tbv = new TextbausteinView(x) {Background = FindResource("ApplicationBackground") as LinearGradientBrush};

                    var rootGrid2 = (Grid) tbv.root.Content;
                    var zielGrid = (Grid)rootGrid2.Children[0];
                    var cb = new CheckBox
                    {
                        Content = "Nur für mich sichtbar", 
                        Margin = new Thickness(3), 
                        HorizontalAlignment = HorizontalAlignment.Left, 
                        VerticalAlignment = VerticalAlignment.Center
                    };

                    if (BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineNurEigeneBearbeiten) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineAlleBearbeiten))
                    {
                        cb.IsEnabled = false;
                    }

                    var IsOnlyForEmployeeBinding = new Binding("NewVM.IsOnlyForEmployee") { Source = tbv.ViewModel, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
                    BindingOperations.SetBinding(cb, ToggleButton.IsCheckedProperty, IsOnlyForEmployeeBinding);

                    Grid.SetColumn(cb, 0);
                    Grid.SetRow(cb, 2);
                    Grid.SetColumnSpan(cb, 4);

                    zielGrid.Children.Add(cb);

                    var stackPanel = new StackPanel {Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right};

                    var speichernBtn = new Button
                    {
                        Content = "Speichern und schließen", 
                        HorizontalAlignment = HorizontalAlignment.Right,
                        Margin = new Thickness(3), 
                        VerticalAlignment = VerticalAlignment.Center
                    };

                    var abbrechenBtn = new Button
                    {
                        Content = "Abbrechen",
                        HorizontalAlignment = HorizontalAlignment.Right,
                        Margin = new Thickness(3),
                        VerticalAlignment = VerticalAlignment.Center
                    };

                    stackPanel.Children.Add(speichernBtn);
                    stackPanel.Children.Add(abbrechenBtn);
                    Grid.SetRow(stackPanel, 2);

                    rootGrid2.Children.Add(stackPanel);
                    tbv.root.Header = string.Empty;
                    var window = new BeWoWindow(tbv) {Width = 514, Height = 400, rootGroupBox = {Header = "Textbausteine"}};

                    speichernBtn.Click += (o, args) =>
                    {
                        tbv.Focus();
                        if (x.IsDirty || x.VMList.Any(vm => vm.IsDirty))
                            tbv.Save(() => { textbausteineSearchView.ServiceCategoryOid = textbausteineSearchView.ServiceCategoryOid; });

                        window.Close();
                    };

                    abbrechenBtn.Click += (o, args) =>
                    {
                        tbv.Focus();
                        tbv.DoSaveCheck();

                        window.Close();
                    };

                    window.Show();
                }));
        }

	    private void EintraegeUmbuchenBtn_Click(object sender, RoutedEventArgs e)
	    {
		    var si = supportConceptSelectionControl.SelectedItem;
		    if (si.SupportConceptTreeNodeDC == null)
		    {
			    MessageBox.Show("Bitte wählen Sie einen Hilfeplan zum Umbuchen von Einträgen aus.", "Kein Hilfeplan gewählt", MessageBoxButton.OK, MessageBoxImage.Exclamation);
			    return;
		    }
			
			var umbuchungsView = new ServiceRecordRebookingView(si.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC) { Background = FindResource("ApplicationBackground") as LinearGradientBrush };
		    if (si.SupportConceptTreeNodeDC.Customer != null)
		    {
			    umbuchungsView.SetSearchText(si.SupportConceptTreeNodeDC.Customer.LastNameFirstName);
		    }
		    var rootGrid2      = (Grid) umbuchungsView.root.Content;
			var stackPanel     = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Bottom};

			var speichernBtn = new Button
			{
				Content = "Umbuchen und schließen",
				HorizontalAlignment = HorizontalAlignment.Right,
				Margin = new Thickness(3),
				VerticalAlignment = VerticalAlignment.Center
			};

			var abbrechenBtn = new Button
			{
				Content = "Abbrechen",
				HorizontalAlignment = HorizontalAlignment.Right,
				Margin = new Thickness(3),
				VerticalAlignment = VerticalAlignment.Center
			};

			stackPanel.Children.Add(speichernBtn);
			stackPanel.Children.Add(abbrechenBtn);
			Grid.SetRow(stackPanel, 1);
			Grid.SetColumnSpan(stackPanel, 2);

			rootGrid2.Children.Add(stackPanel);
			
			var window = new BeWoWindow(umbuchungsView) { Width = 450, Height = 200, rootGroupBox = { Header = "Umbuchung" }, MinHeight = 170, ResizeMode = ResizeMode.NoResize};
			
		    window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
		    window.Owner = Application.Current.MainWindow;

			speichernBtn.Click += (o, args) =>
			{
				if (umbuchungsView.Zielhilfeplan == null)
				{
					MessageBox.Show("Bitte wählen Sie einen Hilfeplan auf den die Einträge umgebucht werden sollen aus.", "Kein Hilfeplan gewählt", MessageBoxButton.OK, MessageBoxImage.Exclamation);
					return;
				}

				umbuchungsView.Focus();
				
				umbuchungsView.Save(records => this.Dispatch(() => ServiceFacade.DoOperationsServiceAsync(s => s.UpdateServiceRecords(records), 
										 () => this.Dispatch(() => ViewModel.BuildServiceRecordsForSelectedTreeNode(true)))));

				window.Close();
			};

			abbrechenBtn.Click += (o, args) =>
			{
				umbuchungsView.Focus();

				window.Close();
			};

			window.ShowDialog();
	    }

	    private void IncreaseFontSizeBtn_Click(object sender, RoutedEventArgs e)
	    {
		    dokumentationsTextBox.FontSize++;
			BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox.FontSize;

            //für notize 2-5
            dokumentationsTextBox2.FontSize++;
            BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox2.FontSize;
            dokumentationsTextBox3.FontSize++;
            BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox3.FontSize;
            dokumentationsTextBox4.FontSize++;
            BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox4.FontSize;
            dokumentationsTextBox5.FontSize++;
            BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox5.FontSize;
	    }

	    private void DecreaseFontSizeBtn_Click(object sender, RoutedEventArgs e)
	    {
            if (dokumentationsTextBox.FontSize <= 1 || dokumentationsTextBox2.FontSize <= 1 || dokumentationsTextBox3.FontSize <= 1 ||
                dokumentationsTextBox4.FontSize <= 1 || dokumentationsTextBox5.FontSize <= 1)
	        {
	            return;
	        }

			dokumentationsTextBox.FontSize--;
			BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox.FontSize;
            dokumentationsTextBox2.FontSize--;
            BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox2.FontSize;
            dokumentationsTextBox3.FontSize--;
            BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox3.FontSize;
            dokumentationsTextBox4.FontSize--;
            BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox4.FontSize;
            dokumentationsTextBox5.FontSize--;
            BeWoApp.AppSettings.DocumentationFontSize = dokumentationsTextBox5.FontSize;
            
            
	    }

		//private void ZeitraumauswahlwechselBtn_Click(object sender, RoutedEventArgs e)
		//{
		//	var nAlt                        = NDayTextbox.Visibility;
		//	NDayTextbox.Visibility          = TimeIntervalComboBox.Visibility;
		//	TimeIntervalComboBox.Visibility = nAlt;
		//	NLadenBtn.Visibility            = NDayTextbox.Visibility;

		//	if (TimeIntervalComboBox.Visibility == Visibility.Visible)
		//	{
		//		var s = (KeyValuePair<object, String>)(TimeIntervalComboBox.SelectedItem ?? ((Dictionary<object, String>) TimeIntervalComboBox.ItemsSource).First());
		//		ViewModel.ServiceRecordTimeInterval = (ServiceRecordTimeInterval) s.Key;
		//	}
		//	else
		//	{
		//		ViewModel.ServiceRecordTimeInterval = ServiceRecordTimeInterval.LastNDays;
		//	}
		//}

	    private void NLadenBtn_Click(object sender, RoutedEventArgs e)
	    {
		    ViewModel.BuildServiceRecordsForSelectedTreeNode(true);
	    }

        private void btnAddEmployee2Wohnheimbuchung_Click(object sender, RoutedEventArgs e)
        {
            popupEmployees.IsOpen = true;
        }

        private void EmployeeSearchView_ItemSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            popupEmployees.IsOpen = false;
            var selectedEmployee = e.Data;

            ViewModel.SelectedWohnheimbuchung.EmployeeList.NewVM.Employee = selectedEmployee;
            ViewModel.SelectedWohnheimbuchung.EmployeeList.AddNewVMToList();

            BeWoWpfUtils.RefreshDXGrid(Employee2WohnheimbuchungGridControl);
        }

        private void SupportConceptForWohnheimbuchungSearchView_ItemSelected(object sender, EventArgs<CompactSupportConceptDC> e)
        {
            popupSupportConcepts.IsOpen = false;
            var selectedSupportConcept = e.Data;

            ServiceFacade.DoCustomerServiceAsync(s => s.LoadSupportConcept(selectedSupportConcept.SupportConceptOid), sc => this.Dispatch(delegate
            {
                ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.NewVM.Costbearer2SupportConcept = sc.CostBearerRelations.FirstOrDefault(f => f.CostBearer2SupportConceptOid.Equals(selectedSupportConcept.CostBearerRelOids.First()));

                var startDate = DateTime.Now.Date;
                ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.NewVM.StartDate = startDate;
                ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.NewVM.EndDate   = startDate.AddHours(23).AddMinutes(59);

                ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.AddNewVMToList();

                BeWoWpfUtils.RefreshDXGrid(SupportConcept2WohnheimbuchungGridControl);
            }));
        }

        private void btnAddSupportConcept2Wohnheimbuchung_Click(object sender, RoutedEventArgs e)
        {
            popupSupportConcepts.IsOpen = true;
        }

        private void BtnSaveWohnheimbuchung_OnClick(object sender, RoutedEventArgs e)
        {
            if (!ViewModel.SelectedWohnheimbuchung.IsDirty)
            {
                return;
            }

            var lValid = ValidationTrigger.Validate(wohnheimbuchungsGrid);

			
            
            var hasInvalidSupportConceptRelTimeSpans = ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.VMList.Any(a => a.StartDate > a.EndDate);
            var hasInvalidEmployeeRelTimeSpans       = ViewModel.SelectedWohnheimbuchung.EmployeeList.VMList.Any(a => a.StartDate > a.EndDate);

            if (hasInvalidEmployeeRelTimeSpans || hasInvalidSupportConceptRelTimeSpans)
            {
                MessageBox.Show("Die Endzeit darf nicht vor der Startzeit liegen.", "Ungültige Eingabe", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (lValid)
            {
                var wohnheimbuchungDC = ViewModel.SelectedWohnheimbuchung.CommitToDataContract();

                if (ViewModel.SelectedWohnheimbuchung.IsNew)
                {
                    ServiceFacade.DoCustomerServiceAsync(s => s.InsertWohnheimbuchung(wohnheimbuchungDC), wb => this.Dispatch(() => CreateServiceRecordsFromWohnheimbuchung(wb, x => ReloadWohnheimbuchungen(wb))));
                }
                else if (ViewModel.SelectedWohnheimbuchung.EmployeeList.VMList.IsEmpty() && ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.VMList.IsEmpty() && !ViewModel.SelectedWohnheimbuchung.IsNew)
                {
                    ServiceFacade.DoCustomerServiceAsync(s => s.FindWohnheimbuchungsServiceRecords(ViewModel.SelectedWohnheimbuchung.DataContract.WohnheimbuchungOid.Value), bestehendeEintraege =>
                    {
                        ServiceFacade.DoOperationsServiceSync(s2 => s2.DeleteServiceRecords(bestehendeEintraege.ToDictionary(sr2 => sr2.ServiceRecordOid.Value, sr2 => sr2.ServiceRecordVersion.Value)));
                        ServiceFacade.DoCustomerServiceSync(s3 => s3.DeleteWohnheimbuchung(ViewModel.SelectedWohnheimbuchung.DataContract.WohnheimbuchungOid.Value, ViewModel.SelectedWohnheimbuchung.DataContract.WohnheimbuchungVersion.Value));
                        ViewModel.RefreshServiceRecordsForSelectedTreeNode();
                        ViewModel.SelectedWohnheimbuchung = new WohnheimbuchungsVM(new WohnheimbuchungDC(), ViewModel.PrototypeVM.Category2Services) {Buchungsdatum = ViewModel.SelectedWohnheimbuchung.Buchungsdatum, Wohnheim = ViewModel.SelectedWohnheimbuchung.Wohnheim};
                    });
                }
                else
                {
                    ServiceFacade.DoCustomerServiceAsync(s => s.UpdateWohnheimbuchung(wohnheimbuchungDC), wb => this.Dispatch(() => CreateServiceRecordsFromWohnheimbuchung(wb, x => ReloadWohnheimbuchungen(wb))));
                }
            }
            else
            {
                var message = ViewModel.SelectedWohnheimbuchung.ServiceDescription == null ? "Bitte geben Sie eine Kategorie und eine Leistung an." : "Bitte geben Sie eine gültige Uhrzeit ein.";

                MessageBox.Show(message, "Ungültige Eingabe", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CreateServiceRecordsFromWohnheimbuchung(long pWohnheimbuchungsOid, Action<long> callBack)
        {
            //ServiceFacade.DoCustomerServiceAsync(s => s.CreateServiceRecordsFromWohnheimbuchung(pWohnheimbuchungsOid, ViewModel.SelectedWohnheimbuchung.ServiceDescription.ServiceDescriptionOid.Value), 
            ServiceFacade.DoCustomerServiceAsync(s => s.CreateServiceRecordsFromWohnheimbuchung(pWohnheimbuchungsOid, 0),
                r => this.Dispatch(() =>
                {
                    callBack(pWohnheimbuchungsOid);
                    ViewModel.RefreshServiceRecordsForSelectedTreeNode();
                }));
        }
        
        public void ReloadWohnheimbuchungen(long? pOid)
        {
            VMFactory.CreateWohnheimbuchungsVMAsync(pOid, wb => this.Dispatch(delegate
            {
                LoadExistingWohnheimbuchung(foundExistingBuchung => this.Dispatch(() => { }));
            }));
        }

        private void WohnheimbuchungsDateEdit_OnEditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            if (chkWohnheimBooking.IsChecked.HasValue && chkWohnheimBooking.IsChecked.Value)
            {
                UpdateWohnheimBuchungGrid();
            }
        }

        private void LoadExistingWohnheimbuchung(Action<bool> callback)
        {
            var wohnheim      = (CompactWohnheimDC) wohnheimbuchungsWohnheimComboBox.SelectedItem;
            var buchungsdatum = (DateTime?) wohnheimbuchungsDateEdit.EditValue;

            if (wohnheim == null || buchungsdatum == null)
            {
                return;
            }

            ViewModel.LoadExistingWohnheimbuchung(wohnheim, buchungsdatum.Value, callback);
        }

        private void WohnheimbuchungsWohnheimComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var comboBox         = (ComboBox) sender;
            var selectedWohnheim = (CompactWohnheimDC) (comboBox.SelectedItem ?? comboBox.SelectionBoxItem);

            btnAddSupportConcept.IsEnabled           = true;
            btnAddEmployee2Wohnheimbuchung.IsEnabled = true;

            if (chkWohnheimBooking.IsChecked.HasValue && chkWohnheimBooking.IsChecked.Value)
            {
                PreselectSupportConceptsFromWohnheim(selectedWohnheim);
                LoadExistingWohnheimbuchung(foundExistingBuchung => this.Dispatch(() => { }));
            }
        }

        private void PreselectSupportConceptsFromWohnheim(CompactWohnheimDC wohnheim)
        {
            if (supportConceptForWohnheimbuchungSearchView.SupportConcepts != null && wohnheim != null)
            {
                supportConceptForWohnheimbuchungSearchView.HiddenSupportConcepts =
                    supportConceptForWohnheimbuchungSearchView.SupportConcepts.Where(
                        w => !wohnheim.CustomerOids.Contains(w.Customer.CustomerOid)).ToList();
            }
        }

        private void Button_deleteSupportConcept2WohnheimbuchungClick(object sender, RoutedEventArgs e)
        {
            ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.VMList.Remove(SupportConcept2WohnheimbuchungGridControl.GetCurrentValue<WohnheimbuchungCostbearerSupportConceptRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(SupportConcept2WohnheimbuchungGridControl);
        }

        private void Button_Employee2WohnheimbuchungClick(object sender, RoutedEventArgs e)
        {
            ViewModel.SelectedWohnheimbuchung.EmployeeList.VMList.Remove(Employee2WohnheimbuchungGridControl.GetCurrentValue<WohnheimbuchungEmployeeRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(Employee2WohnheimbuchungGridControl);
        }

        private void Speicher_Schliessen_Button_OnMouseEnter(object sender, MouseEventArgs e)
        {
            var buchung = ViewModel.SelectedWohnheimbuchung;

            if (ViewModel.SelectedWohnheimbuchung.Buchungsdatum != null && 
                ViewModel.SelectedWohnheimbuchung.Wohnheim != null && 
                ViewModel.SelectedWohnheimbuchung.EmployeeList.VMList.Any() && 
                ViewModel.SelectedWohnheimbuchung.Wohnheimbuchung2Costbearer2SupportConceptList.VMList.Any())
            {
                btnSaveWohnheimbuchung.IsEnabled = true;
            }
            else
            {
                btnSaveWohnheimbuchung.IsEnabled = false;
            }

            if (!buchung.IsNew && !buchung.EmployeeList.VMList.Any() && !buchung.Wohnheimbuchung2Costbearer2SupportConceptList.VMList.Any())
            {
                btnSaveWohnheimbuchung.IsEnabled = true;
            }
        }

        private void VollbildDokuButton_OnClick(object sender, RoutedEventArgs e)
        {
            var stackPanel = new StackPanel {Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Left};

            var schriftVergroessern   = new Button {Margin = new Thickness(3), HorizontalAlignment = HorizontalAlignment.Left, Content = "A+"};
            var schriftVerkleinern    = new Button {Margin = new Thickness(3), HorizontalAlignment = HorizontalAlignment.Left, Content = "A-"};
            var textbausteineOptionen = new Button {Margin = new Thickness(3), HorizontalAlignment = HorizontalAlignment.Left, Content = "@", FontFamily = new FontFamily("Webdings")};
            var textbausteine         = new Button {Margin = new Thickness(3), HorizontalAlignment = HorizontalAlignment.Left, Content = "Textbausteine"};
            
            textbausteineOptionen.Click += EditTextbausteineClick;
            textbausteine.Click         += ButtonBase_OnClick;

			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineAlleAnsehen) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineNurEigeneAnsehen))
			{
				textbausteine.Visibility = Visibility.Collapsed;
				textbausteineOptionen.Visibility = Visibility.Collapsed;
			}
			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineAlleBearbeiten) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineNurEigeneBearbeiten))
			{
				textbausteineOptionen.Visibility = Visibility.Collapsed;
			}

            stackPanel.Children.Add(schriftVergroessern);
            stackPanel.Children.Add(schriftVerkleinern);
            stackPanel.Children.Add(textbausteineOptionen);
            stackPanel.Children.Add(textbausteine);

            if (TabItem1_Notice.IsSelected)
            {
                grosseDokuTextBox = new TextBox
                {
                    AcceptsReturn                 = true,
                    VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                    TextWrapping                  = TextWrapping.Wrap,
                    Language                      = dokumentationsTextBox.Language,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,
                    AutoWordSelection             = true,
                    FontSize                      = dokumentationsTextBox.FontSize,
                    Text                          = dokumentationsTextBox.Text
                                     
                }; 
            }
            else if (TabItem2_Notice.IsSelected) {
                grosseDokuTextBox = new TextBox
                {
                    AcceptsReturn                 = true,
                    VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                    TextWrapping                  = TextWrapping.Wrap,
                    Language                      = dokumentationsTextBox2.Language,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,
                    AutoWordSelection             = true,
                    FontSize                      = dokumentationsTextBox2.FontSize,
                    Text                          = dokumentationsTextBox2.Text
               
                };
            }
            else if (TabItem3_Notice.IsSelected)
            {
                grosseDokuTextBox = new TextBox
                {
                    AcceptsReturn                 = true,
                    VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                    TextWrapping                  = TextWrapping.Wrap,
                    Language                      = dokumentationsTextBox3.Language,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,
                    AutoWordSelection             = true,
                    FontSize                      = dokumentationsTextBox3.FontSize,
                    Text                          = dokumentationsTextBox3.Text
                };          
            }
            else if (TabItem4_Notice.IsSelected)
            {
                grosseDokuTextBox = new TextBox
                {
                    AcceptsReturn                 = true,
                    VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                    TextWrapping                  = TextWrapping.Wrap,
                    Language                      = dokumentationsTextBox4.Language,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,
                    AutoWordSelection             = true,
                    FontSize                      = dokumentationsTextBox4.FontSize,
                    Text                          = dokumentationsTextBox4.Text                 
                };
               
            }
            else if (TabItem5_Notice.IsSelected)
            {
                grosseDokuTextBox = new TextBox
                {
                    AcceptsReturn                 = true,
                    VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                    TextWrapping                  = TextWrapping.Wrap,
                    Language                      = dokumentationsTextBox5.Language,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,
                    AutoWordSelection             = true,
                    FontSize                      = dokumentationsTextBox5.FontSize,
                    Text                          = dokumentationsTextBox5.Text                 
                };
            }

            schriftVergroessern.Click += delegate(object o, RoutedEventArgs args)
            {
                IncreaseFontSizeBtn_Click(o, args);
                grosseDokuTextBox.FontSize = dokumentationsTextBox.FontSize;
            };

            schriftVerkleinern.Click += delegate(object o, RoutedEventArgs args)
            {
                DecreaseFontSizeBtn_Click(o, args);
                grosseDokuTextBox.FontSize = dokumentationsTextBox.FontSize;
            };

            Grid.SetRow(stackPanel, 0);
            Grid.SetRow(grosseDokuTextBox, 1);

            grosseDokuTextBox.SpellCheck.IsEnabled = true;

            if (TabItem1_Notice.IsSelected)
            {
                grosseDokuTextBox.TextChanged += delegate { dokumentationsTextBox.Text = grosseDokuTextBox.Text; };
            }
            else if (TabItem2_Notice.IsSelected)
            {
                grosseDokuTextBox.TextChanged += delegate { dokumentationsTextBox2.Text = grosseDokuTextBox.Text; };
            }
            else if (TabItem3_Notice.IsSelected)
            {
                grosseDokuTextBox.TextChanged += delegate { dokumentationsTextBox3.Text = grosseDokuTextBox.Text; };
            }
            else if (TabItem4_Notice.IsSelected)
            {
                grosseDokuTextBox.TextChanged += delegate { dokumentationsTextBox4.Text = grosseDokuTextBox.Text; };
            }
            else if (TabItem5_Notice.IsSelected)
            {
                grosseDokuTextBox.TextChanged += delegate { dokumentationsTextBox5.Text = grosseDokuTextBox.Text; };
            }


            var rootGrid2 = new Grid();
            rootGrid2.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});
            rootGrid2.RowDefinitions.Add(new RowDefinition {Height = new GridLength(1, GridUnitType.Star)});
            rootGrid2.Children.Add(stackPanel);
            rootGrid2.Children.Add(grosseDokuTextBox);

            var neunzigProzentHoehe  = MainControl.ActualHeight * .9;
            var neunzigProzentBreite = MainControl.ActualWidth * .9;

            var beWoWindow = new BeWoWindow(rootGrid2) { Width = neunzigProzentBreite, Height = neunzigProzentHoehe, rootGroupBox = { Header = "Dokumentation" }, WindowStartupLocation = WindowStartupLocation.CenterScreen};


            beWoWindow.Closed += delegate {
                grosseDokuTextBox = null;
            };

            beWoWindow.ShowDialog();
        }





        // Bedarfsmedikation
        

        private void ChkBedarfsmedikationChecked(object sender, RoutedEventArgs e)
        {
            chkWithClient.IsEnabled      = false;
            chkMultiBooking.IsEnabled    = false;
            chkGroupBooking.IsEnabled    = false;
            chkWohnheimBooking.IsEnabled = false;

            WithoutClient = true;
            SelectedItemChanged(null);

            customerDetailGrid.Visibility        = Visibility.Collapsed;
            zeitraumGrid.Visibility              = Visibility.Collapsed;
            customerSelectAndInfoGrid.Visibility = Visibility.Collapsed;
            wohnheimbuchungsGrid.Visibility      = Visibility.Collapsed;
            btnSaveWohnheimbuchung.Visibility    = Visibility.Collapsed;
            BedarfsmedikationsGrid.Visibility    = Visibility.Visible;

            if (DarrFormCBE.SelectedIndex == -1 && ServiceRecordListVM.AllDosageForms.Count > 0)
            {
                DarrFormCBE.SelectedIndex = 0;
            }
        }

        private void ChkBedarfsmedikationUnchecked(object sender, RoutedEventArgs e)
        {
            chkWithClient.IsEnabled      = true;
            chkMultiBooking.IsEnabled    = true;
            chkGroupBooking.IsEnabled    = true;
            chkWohnheimBooking.IsEnabled = true;

            WithoutClient = false;

            if (supportConceptSelectionControl != null)
            {
                var selectedNode = supportConceptSelectionControl.SelectedItem;
                SelectedItemChanged(selectedNode);
            }

            customerDetailGrid.Visibility        = Visibility.Visible;
            zeitraumGrid.Visibility              = Visibility.Visible;
            customerSelectAndInfoGrid.Visibility = Visibility.Visible;
            wohnheimbuchungsGrid.Visibility      = Visibility.Collapsed;
            btnSaveWohnheimbuchung.Visibility    = Visibility.Collapsed;
            BedarfsmedikationsGrid.Visibility    = Visibility.Collapsed;
        }

        private void CustomerSelectionControl_ItemSelected(object sender, EventArgs<CompactCustomerDC> e)
        {
            VMFactory.CreateMedRecordVMAsync(e.Data.CustomerOid, medRecords => this.Dispatch(() =>
            {
                ViewModel.BedarfsMedViewModel                = medRecords;
                ViewModel.BedarfsMedViewModel.NewVM.Customer = e.Data;

                ViewModel.BedarfsMedViewModel.NewVM.SetInitialDosageForm(ServiceRecordListVM.AllDosageForms.FirstOrDefault());
            }));
        }

        private void PopupeditEmployeeBedarfsMedPopUpClick(object sender, RoutedEventArgs e)
        {
            popupMedRecordEmployees.IsOpen = true;
        }

        private void Popupedit_employee_bedarfsmed_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View) || ViewModel.BedarfsMedViewModel == null)
            {
                return;
            }

            var employeeCompact = ViewModel.BedarfsMedViewModel.NewVM.Employee;

            VMFactory.CreateEmployeeVMAsync(employeeCompact.EmployeeOid,
                cb => this.Dispatch(
                    () => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, ServiceRecordView2>(cb, this, () => this.Dispatch(
                    () => BeWoUtils.UpdateAllViews(employeeCompact)))));
        }

        private void ButtonSaveMedRecord_Click(object sender, RoutedEventArgs e)
        {
            var newMedRecordIsValid = Validate(NewMedRecordGrid);

            if(ViewModel.BedarfsMedViewModel.NewVM.Employee == null)
            {
                MessageBox.Show("Bitte wählen Sie einen Mitarbeiter aus.", "Fehler beim Anlegen", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            
            if (newMedRecordIsValid)
            {
                var currentDosageForm = ViewModel.BedarfsMedViewModel.NewVM.DosageForm;

                var currentCustomer = ViewModel.BedarfsMedViewModel.NewVM.Customer;
                var currentEmployee = ViewModel.BedarfsMedViewModel.NewVM.Employee;

                ViewModel.BedarfsMedViewModel.AddNewVMToList();
                ViewModel.BedarfsMedViewModel.NewVM.SetInitialDosageForm(currentDosageForm);

                ServiceFacade.DoCustomerServiceAsync(s => s.InsertMedRecords(ViewModel.BedarfsMedViewModel.CommitAdded()), x => this.Dispatch(() => ReloadMedRecordViewModel(currentCustomer, currentEmployee)));
            }
        }

        private void ReloadMedRecordViewModel(CompactCustomerDC pCustomer, CompactEmployeeDC pEmployee)
        {
            VMFactory.CreateMedRecordVMAsync(pCustomer.CustomerOid, medRecords => this.Dispatch(() =>
            {
                ViewModel.BedarfsMedViewModel = medRecords;
                ViewModel.BedarfsMedViewModel.NewVM.Customer = pCustomer;
                ViewModel.BedarfsMedViewModel.NewVM.Employee = pEmployee;

                ViewModel.BedarfsMedViewModel.NewVM.SetInitialDosageForm(ServiceRecordListVM.AllDosageForms.FirstOrDefault());
            }));
        }

        private void MedRecordEmployeeSearchView_OnItemSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            popupMedRecordEmployees.IsOpen     = false;
            popupedit_employee_bedarfsmed.Text = e.Data.ToString();

            ViewModel.BedarfsMedViewModel.NewVM.Employee = e.Data;
        }

        private void MedRecord_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ShowMedRecordEditView();
        }

        private void ShowMedRecordEditView()
        {
            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.MedRecordsAendern) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.EditAll))
            {
                return;
            }

            var currentMedRecord = (MedRecordVM)MedRecordGridControl.CurrentItem;
            var currentEmployee = currentMedRecord.Employee;
            var currentCustomer = currentMedRecord.Customer;
            var medRecord2Edit = new MedRecordVM(currentMedRecord.CommitToDataContract());

            var medRecordEditView = new MedRecordEditView(medRecord2Edit);

            popup_content.Child = medRecordEditView;

            double height = 270;
            double width = 800;

            popup_content.Child = medRecordEditView;

            if (rootGrid.ActualWidth < width)
            {
                width = rootGrid.ActualWidth;
            }

            if (rootGrid.ActualHeight < height)
            {
                height = rootGrid.ActualHeight;
            }

            popup_content.Width = width;
            popup_content.Height = height;

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

                        ClosePopupView();
                    }));

                medRecordEditView.CommandBindings.Add(new CommandBinding(
                    ApplicationCommands.Save, (s, e2) =>
                    {
                        var isValid = medRecordEditView.IsValid();

                        if (!isValid)
                        {
                            return;
                        }

                        if (!medRecordEditView.ViewModel.Customer.Equals(currentCustomer))
                        {
                            var messageBoxResult = MessageBox.Show("Möchten Sie diesen Eintrag wirklich auf Klient " + medRecordEditView.ViewModel.Customer.FullName + " umbuchen?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Question);

                            if (messageBoxResult.Equals(MessageBoxResult.No))
                            {
                                return;
                            }
                        }

                        medRecordEditView.SaveData();
                        ClosePopupView();

                        ReloadMedRecordViewModel(currentCustomer, currentEmployee);
                    }));
            }

            medRecordEditView.ParentView = this;
            SetPopupViewVisible(true);
        }

        private void Button_deleteMedRecordClick(object sender, RoutedEventArgs e)
        {
            var messageBoxResult = MessageBox.Show("Sind Sie sicher, dass Sie diese Bedarfsmedikation löschen möchten?", "Eintrag löschen", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (messageBoxResult.Equals(MessageBoxResult.No))
            {
                return;
            }

            var medRecord2Delete = (MedRecordVM) MedRecordGridControl.CurrentItem;

            ViewModel.BedarfsMedViewModel.VMList.Remove(medRecord2Delete);

            var mrDC = medRecord2Delete.CommitToDataContract();

            ServiceFacade.DoCustomerServiceSync(s => s.DeleteMedRecord(mrDC.MedRecordOid.Value, mrDC.MedRecordVersion.Value));

            ReloadMedRecordViewModel(ViewModel.BedarfsMedViewModel.NewVM.Customer, ViewModel.BedarfsMedViewModel.NewVM.Employee);
        }

        private void PopupInfoMedRecord_OnOpened(object sender, EventArgs e)
        {
            dxDeleteButtonMedRecord.IsEnabled = BeWoApp.LoggedOnUser.HasRight(UserRightType.MedRecordsLoeschen) || BeWoApp.LoggedOnUser.HasRight(UserRightType.DeleteAll);
            dxEditButtonMedRecord.IsEnabled   = BeWoApp.LoggedOnUser.HasRight(UserRightType.MedRecordsAendern) || BeWoApp.LoggedOnUser.HasRight(UserRightType.EditAll);
        }

        private void DxEditButtonMedRecord_OnItemClick(object sender, ItemClickEventArgs e)
        {
            ShowMedRecordEditView();
        }

        private void DxDeleteButtonMedRecord_OnItemClick(object sender, ItemClickEventArgs e)
        {
            var messageBoxResult = MessageBox.Show("Sind Sie sicher, dass Sie diese Bedarfsmedikation löschen möchten?", "Eintrag löschen", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (messageBoxResult.Equals(MessageBoxResult.No))
            {
                return;
            }

            var medRecord2Delete = (MedRecordVM)MedRecordGridControl.CurrentItem;

            ViewModel.BedarfsMedViewModel.VMList.Remove(medRecord2Delete);

            var mrDC = medRecord2Delete.CommitToDataContract();

            ServiceFacade.DoCustomerServiceSync(s => s.DeleteMedRecord(mrDC.MedRecordOid.Value, mrDC.MedRecordVersion.Value));

            ReloadMedRecordViewModel(ViewModel.BedarfsMedViewModel.NewVM.Customer, ViewModel.BedarfsMedViewModel.NewVM.Employee);
        }
    }
}