using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
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.Threading;

using BeWo.Annotations;
using BeWo.Controls;
using BeWo.Core;
using BeWo.Core.Service;
using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.ViewModel;

using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.ClientPartials;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;
using DevExpress.Utils;
using DevExpress.Xpf.Editors.Settings;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Editors;

namespace BeWo.View.Detail
{
    public partial class SupportConceptView : INotifyPropertyChanged
    {
        #region Constants and Fields

        private TreeViewItem _SelectedGoalTreeNode;
        
        private PersonView _PersonModalPopUp;

        private List<ServiceRecordDC> _ServiceRecords;

        private SupportConceptVM _ViewModel;

        private bool employeeEditFlag;

	    private bool isChangingCostbearer;

	    private SupportConceptCostBearerRelVM supportConceptCostBearerRel2Change;

		#region Rechtebinding
		public static bool IsAllowedToChangeCostbeaerer
	    {
		    get { return BeWoApp.LoggedOnUser.HasRight(UserRightType.CostbearerAllowChange); }
	    }

	    public static bool IsAllowedToEditCostbearers
	    {
		    get { return BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConceptView_Edit); }
	    }

	    public static bool IsAllowedToEditGoals
	    {
			get { return BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConcept_AllowEditGoals); }
	    }
		#endregion

		#endregion

		#region Constructors and Destructors

		public SupportConceptView(SupportConceptVM pViewModel)
        {
            InitializeComponent();
            ViewModel = pViewModel;

			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConceptView_AllowArchiving))
			{
				lblArchiviert.Visibility = Visibility.Hidden;
				chkArchiviert.Visibility = Visibility.Hidden;
			}
			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.DocumentsAllowViewAll) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.DokumenteHilfeplaene))
			{
				tabitem_documents.Visibility = Visibility.Collapsed;
			}
	        if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConceptView_Edit))
			{
				grid_details.IsEnabled = false;
				
				button_addCostBearer.IsEnabled = false;

				//tabitem_documents.IsEnabled = false;

				grid_serviceaccountings.IsEnabled = false;

				tabitem_grid_tasks.IsEnabled = false;

				if (BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConcept_AllowEditTasks))
				{
					tabitem_grid_tasks.IsEnabled = true;
					tabitem_tasks.IsSelected     = true;
				}
		        if (BeWoApp.LoggedOnUser.HasRight(UserRightType.SupportConcept_AllowEditGoals))
		        {
			        tabitem_goals.IsSelected = true;
		        }
	        }

	        // HACK: Force the devexpress grid to end editing when the mouse is over savebutton
            // by setting the focus to another element. 
            this.MouseMove += (s, e) =>
                              {
                                  if (!this.gridViewTasks.IsVisible)
                                  {
                                      return;
                                  }

                                  Point p = e.GetPosition(this.btnSave);

                                  if (p.X >= 0 && p.X < this.btnSave.ActualWidth && p.Y >= 0 && p.Y < this.btnSave.ActualHeight)
                                  {
                                      bool b = this.gridViewTasks.Focus();
                                  }
                              };

        }

        public SupportConceptView(SupportConceptVM pViewModel, TaskDC pTaskToEdit)
            : this(pViewModel)
        {
            if (pTaskToEdit != null)
            {
                this.tabitem_tasks.IsSelected = true;

                var item = this.ViewModel.Tasks.VMList.Single(vm => vm.DataContract.TaskOid.Equals(pTaskToEdit.TaskOid));
                var handle = this.grid_tasks.GetRowHandleByListIndex(this.ViewModel.Tasks.VMList.IndexOf(item));

                // WORKAROUND:  http://www.devexpress.com/Support/Center/p/B36082.aspx
                this.Dispatcher.BeginInvoke(
                                            DispatcherPriority.ApplicationIdle, 
                                            (Action)delegate
                                                    {
                                                        this.gridViewTasks.FocusedRowHandle = handle;
                                                        do
                                                        {
                                                            this.gridViewTasks.MoveNextCell();
                                                        }
                                                        while (!this.gridViewTasks.FocusedColumn.FieldName.Equals("CompletedDate"));
                                                        this.gridViewTasks.ShowEditor();
                                                    });
            }
        }

        #endregion

        #region Properties

        private SupportConceptApprovalPeriodVM _SelectedApprovalPeriodVM;

        public SupportConceptApprovalPeriodVM SelectedApprovalPeriodVM
        {
            get { return _SelectedApprovalPeriodVM; }

            set
            {
                _SelectedApprovalPeriodVM = value;
                OnPropertyChanged("SelectedApprovalPeriodVM");
            }
        }

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

        public override string Title
        {
            get
            {
                return "Hilfepläne";
            }
        }

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

        internal SupportConceptVM ViewModel
        {
            get
            {
                return _ViewModel;
            }

            set
            {
                var i = 0;
                if (tabcontrol_costbearers != null)
                {
                    i = tabcontrol_costbearers.SelectedIndex;
                }

                _ViewModel = value;
                DataContext = value;
                if (ViewModel.Originator != null)
                {
                    popupedit_employee.Text = ViewModel.Originator.ToString();
                }

                if (ViewModel.Customer != null)
                {
                    popupedit_customer.Text = ViewModel.Customer.ToString();
                }

                treeview_Goals.ItemsSource = value.CombinedGoalTree;

                if (tabcontrol_costbearers != null)
                {
                    tabcontrol_costbearers.SelectedIndex = i;
                }

                treeview_serviceAccountings.ItemsSource = value.GlobalServiceTree;
                //this.treeview_individualServiceAccountings.ItemsSource = value.IndividualServiceTree;
            }
        }

        #endregion

        #region Public Methods

        public override void ModalPopUpCloseInvoked()
        {
            this.MainControl.CloseCurrentPopUp();
        }

        public override void ModalPopUpSaveInvoked()
        {
            // TODO nicht  schön, umbauen wenn an weiteren Stellen popup hierachien nötig werden
            if (this._PersonModalPopUp._OrganisationModalPopUp != null)
            {
                this._PersonModalPopUp._OrganisationModalPopUp.SaveData();
            }
            else
            {
                this._PersonModalPopUp.SaveData();
            }
        }

        #endregion

        #region Methods

        protected override UserRightType[] GetSaveDemands()
        {
            return ViewModel.IsNew
                       ? new[]
                         {
                             UserRightType.CreateAll, UserRightType.SupportConceptView_Create
                         }
                       : new[]
                         {
                             UserRightType.EditAll, UserRightType.SupportConceptView_Edit, UserRightType.SupportConcept_AllowEditGoals, UserRightType.SupportConcept_AllowEditTasks
                         };
        }

        protected override void Save()
        {
            if (ViewModel.CostBearerRelations.VMList.Exists(vm => vm.CostBearer == null))
            {
                MessageBox.Show("Bitte wählen Sie einen Kostenträger aus", "Fehlende Eingabe", MessageBoxButton.OK);
                return;
            }

            var mehrAlsHundertProzentBetreuungsschluessel = ViewModel.CostBearerRelations.VMList.Any(a => a.ApprovalPeriodList.VMList.Any(a2 => a2.SupportConceptApprovalEmployeeRelations.VMList.Sum(s => s.Betreuungsschluessel) > 100));
            if (mehrAlsHundertProzentBetreuungsschluessel)
            {
                MessageBox.Show("Die Summe der Anteile liegt bei über 100%. Hinzufügen nicht möglich.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var lDataContract = ViewModel.CommitToDataContract();

            var recordOutOfConcept = true;
            ServiceFacade.DoCustomerServiceSync(s => recordOutOfConcept = s.ServiceRecordOutOfSupportConcept(lDataContract));

            if (recordOutOfConcept)
            {

                if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.BookServiceRecordOutOfSupportConcept))
                {
                    MessageBox.Show("Es existiert mindestens eine Buchung außerhalb des Hilfeplanzeitraums.",
                                    "Speichern nicht möglich", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    var mbResult =
                        MessageBox.Show("Es existiert mindestens eine Buchung außerhalb des Hilfeplanzeitraums.\nMöchten Sie trotzdem speichern?",
                                        "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Warning);

                    if(mbResult.Equals(MessageBoxResult.No))
                        return;
                }
            }

            try
            {
                #region Neue Individuelle Ziele speichern
                var neueZM = ViewModel.CombinedGoals.VMList.Where(w => w.IsNew);
                ViewModel.TreeViewItemsList = new List<SupportConceptGoalTreeItem>();
                ViewModel.GetAllTreeViewItems();

                var obersteZiele = neueZM.Where(w => w.IsNew && (w.ParentEntry != null && w.ParentEntry.ValueListEntryOid != null) || w.ParentEntry == null).ToList();

                var alleNeuenZiele = new List<ValueListEntryDC>();
                foreach (var ziel in obersteZiele)
                {
                    var treeItem = ViewModel.TreeViewItemsList.FirstOrDefault(f => f.GoalEntryVM != null && f.GoalEntryVM.Equals(ziel));
                    if (treeItem != null)
                    {
                        alleNeuenZiele.AddRange(GoalService.SaveIndividualGoalsAndMassnahmenRecursively(treeItem));
                    }
                }

                ViewModel.CombinedGoals.VMList.RemoveRange(ViewModel.CombinedGoals.VMList.Where(w => w.IsNew));

                foreach (var zielDC in alleNeuenZiele)
                {
                    ViewModel.CombinedGoals.VMList.Add(new ValueListEntryVM(zielDC));
                }
                #endregion

                lDataContract = ViewModel.CommitToDataContract();

                if (ViewModel.IsNew)
                {
                    ServiceFacade.DoCustomerServiceAsync(s => s.InsertNewSupportConcept(lDataContract), ReloadViewModel);
                }
                else
                {
                    ServiceFacade.DoCustomerServiceAsync(s => s.UpdateSupportConcept(lDataContract), ReloadViewModel);
                }

                Cache.GetInstance().ClearSupportConceptTree();
                BeWoApp.MainControl.ResetView(UIContext.SupportConcept);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void Button_Loaded(object sender, RoutedEventArgs e)
        {
            var t = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher) {Interval = TimeSpan.FromSeconds(.5)};
            t.Tick += delegate
                      {
                          ((Button)sender).Click += add_edit_employee_Click;
                          t.Stop();
                      };
            t.Start();
        }

        private void CostBearerSearchView_OrganisationSelected(object sender, EventArgs<CompactOrganisationDC> e)
        {
            popup_costbearer.IsOpen = false;

            if (ViewModel.CostBearerRelations.VMList.Exists(vm => vm.CostBearer != null && vm.CostBearer.CostBearerOid.Equals(e.Data.CostBearerOid)))
            {
                MessageBox.Show("Dieser Kostenträger wurde bereits hinzugefügt.", "Zufügen nicht möglich", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

	        if (!isChangingCostbearer)
	        {
		        var newVm = ViewModel.CostBearerRelations.NewVM;
		        newVm.CostBearer = e.Data;

		        if (ViewModel.Customer != null && string.IsNullOrEmpty(newVm.CustomerReferenceNumber) &&
		            ViewModel.Customer.CostBearerReferenceNumbers.ContainsKey(e.Data.CostBearerOid.Value))
		        {
			        newVm.CustomerReferenceNumber = ViewModel.Customer.CostBearerReferenceNumbers[e.Data.CostBearerOid.Value];
		        }

		        ViewModel.CostBearerRelations.AddNewVMToList();
		        tabcontrol_costbearers.SelectedIndex = tabcontrol_costbearers.Items.Count - 1;

		        AddNewApprovalPeriod(newVm);
	        }
	        else
	        {
		        supportConceptCostBearerRel2Change.CostBearer = e.Data;

		        if (ViewModel.Customer != null && ViewModel.Customer.CostBearerReferenceNumbers.ContainsKey(e.Data.CostBearerOid.Value))
		        {
			        supportConceptCostBearerRel2Change.CustomerReferenceNumber = ViewModel.Customer.CostBearerReferenceNumbers[e.Data.CostBearerOid.Value];
		        }
		        else
		        {
			        supportConceptCostBearerRel2Change.CustomerReferenceNumber = null;
		        }

		        supportConceptCostBearerRel2Change.CostBearerContactPerson = null;
	        }

	        isChangingCostbearer               = false;
	        supportConceptCostBearerRel2Change = null;
        }

        private void CustomerSearchView_CustomerSelected(object sender, EventArgs<CompactCustomerDC> e)
        {
            popup_customer.IsOpen = false;
            popupedit_customer.Focus();

            var newCustomer = e.Data;

            if (ViewModel.Customer != null && !ViewModel.Customer.Equals(newCustomer))
            {
                if (!ViewModel.IsNew)
                {
                    if (HasServiceRecords(ViewModel))
                    {
                        MessageBox.Show(
                                        "Für diesen Klienten wurden bereits Leistungen hinterlegt. Sie müssen diese Leistungen erst löschen bevor Sie den Klient wechseln können.", 
                                        "Fehler", 
                                        MessageBoxButton.OK, 
                                        MessageBoxImage.Exclamation);
                        return;
                    }
                }
            }

            ViewModel.Customer = e.Data;
        }

        private void EmployeeSearchView_EmployeeSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            popup_employee.IsOpen = false;

            if (!tabitem_tasks.IsSelected)
            {
                ViewModel.Originator = e.Data;
                popupedit_employee.Focus();
                popupedit_employee.Text = e.Data.ToString();
            }
            else
            {
                if (employeeEditFlag)
                {
                    RowData data = grid_tasks.View.FocusedRowData;

                    if (data != null && data.RowHandle != null)
                    {
                        var vm = grid_tasks.GetRow(data.RowHandle.Value) as TaskVM;

                        if (!vm.Employees.Exists(i => i.EmployeeOid.Equals(e.Data.EmployeeOid)))
                        {
                            vm.Employees.Add(e.Data);
                        }
                    }
                }
                else if (!ViewModel.Tasks.NewVM.Employees.Exists(i => i.EmployeeOid.Equals(e.Data.EmployeeOid)))
                {
                    ViewModel.Tasks.NewVM.Employees.Add(e.Data);
                }

                employeeEditFlag = false;
            }
        }

        private List<ServiceRecordDC> GetServiceRecords()
        {
            if (_ServiceRecords == null && ViewModel.Customer != null)
            {
                _ServiceRecords = ViewModel.IsArchived 
                    ? ServiceFacade.DoOperationsServiceSync(s => s.GetCustomerServiceRecords(ViewModel.Customer.CustomerOid, true)) 
                    : ServiceFacade.DoOperationsServiceSync(s => s.GetCustomerServiceRecords(ViewModel.Customer.CustomerOid, false));
            }

            return _ServiceRecords;
        }

        private bool HasServiceRecords(SupportConceptCostBearerRelVM relVM)
        {
            var records = GetServiceRecords();

            if (records != null)
            {
                return records.Where(srDC => srDC.SupportConcept != null && srDC.CostBearer != null && relVM.CostBearer != null)
                    .Any(srDC => srDC.SupportConcept.SupportConceptOid == ViewModel.DataContract.SupportConceptOid && relVM.CostBearer.CostBearerOid == srDC.CostBearer.CostBearerOid);
            }

            return false;
        }

        private bool HasServiceRecords(SupportConceptVM vm)
        {
            var records = GetServiceRecords();

            if (records != null && records.Count > 0)
            {
                return records.Where(srDC => srDC.SupportConcept != null).Any(srDC => srDC.SupportConcept.SupportConceptOid == vm.DataContract.SupportConceptOid);
            }

            return false;
        }

        private void ReloadViewModel(long pOID)
        {
            // reload to update version informations and oid
            VMFactory.CreateSupportConceptVMAsync(pOID, cb => this.Dispatch(delegate { ViewModel = cb; }));
        }

        private void _PersonModalPopUp_PersonSavedOrUpdated(object sender, EventArgs<PersonVM> e)
        {
            ServiceFacade.DoCustomerServiceAsync(
                s => s.LoadPersonCompact(e.Data.DataContract.PersonOid.Value),
                p => this.Dispatch(
                    delegate
                    {
                        var cbRelVM = tabcontrol_costbearers.SelectedItem as SupportConceptCostBearerRelVM;
                        cbRelVM.CostBearerContactPerson = p;
                        MainControl.CloseCurrentPopUp();
                    }));
        }

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

        private void btn_deleteApprovalPeriod_Click(object sender, RoutedEventArgs e)
        {
            var vm = ((Button)sender).Tag as SupportConceptApprovalPeriodVM;
            var cbRelVM = tabcontrol_costbearers.SelectedItem as SupportConceptCostBearerRelVM;

            if (cbRelVM.ApprovalPeriodList.VMList.Count == 1)
            {
                MessageBox.Show("Diese Bewilligungsperiode kann nicht gelöscht werden da mindestens eine vorhanden sein muss.");
                return;
            }

            cbRelVM.ApprovalPeriodList.VMList.Remove(vm);
        }

        private void btn_deleteCBRel_Click(object sender, RoutedEventArgs e)
        {
            var cbRelVM = tabcontrol_costbearers.SelectedItem as SupportConceptCostBearerRelVM;

            if (HasServiceRecords(cbRelVM))
            {
                MessageBox.Show(
                                "Für diesen Kostenträger wurden bereits Leistungen hinterlegt. Sie müssen diese Leistungen erst löschen bevor Sie den Kostenträger entfernen können.", 
                                "Löschen", 
                                MessageBoxButton.OK, 
                                MessageBoxImage.Exclamation);
                return;
            }

            ViewModel.CostBearerRelations.VMList.Remove(cbRelVM);
        }

        private void button_addApprovalPeriod_Click(object sender, RoutedEventArgs e)
        {
            AddNewApprovalPeriod(((Button)sender).Tag as SupportConceptCostBearerRelVM);
        }

        private static void AddNewApprovalPeriod(SupportConceptCostBearerRelVM vm)
        {
            //var cbRelVM = this.tabcontrol_costbearers.SelectedItem as SupportConceptCostBearerRelVM;
			//var actual = cbRelVM.ApprovalPeriodList.VMList.OrderByDescending(i => i.StartDate).FirstOrDefault();

			//if (actual != null)
			//{
			//    vm.ApprovalPeriodList.NewVM.StartDate = vm.StartDate;
			//    vm.ApprovalPeriodList.NewVM.EndDate = vm.EndDate;
			//    vm.ApprovalPeriodList.NewVM.ApprovedBEInterval = actual.ApprovedBEInterval;
			//    vm.ApprovalPeriodList.NewVM.ApprovedBEPerInterval = actual.ApprovedBEPerInterval;
			//    vm.ApprovalPeriodList.NewVM.ApprovedBETotal = actual.ApprovedBETotal;
			//    vm.ApprovalPeriodList.NewVM.ApprovedFixedAmount = actual.ApprovedFixedAmount;
			//    vm.ApprovalPeriodList.NewVM.ApprovedFixedAmountInterval = actual.ApprovedFixedAmountInterval;
			//    vm.ApprovalPeriodList.NewVM.IsApprovedBEShifting = actual.IsApprovedBEShifting;
			//    vm.ApprovalPeriodList.NewVM.IsApprovedFixedAmountShifting = actual.IsApprovedFixedAmountShifting;
			//    vm.ApprovalPeriodList.NewVM.MonthlyPayment = actual.MonthlyPayment;
			//    vm.ApprovalPeriodList.NewVM.ServiceUnitName = actual.ServiceUnitName;

			//    //actual.StartDate = DateTime.Now.Date.AddDays(1);
			//    //actual.EndDate = vm.ApprovedEndDate;
			//}
			//else
			//{
                vm.ApprovalPeriodList.NewVM.StartDate                     = vm.StartDate;
                vm.ApprovalPeriodList.NewVM.EndDate                       = vm.EndDate;
                vm.ApprovalPeriodList.NewVM.ApprovedBEInterval            = SupportConceptApprovalInterval.Weekly;
                vm.ApprovalPeriodList.NewVM.IsApprovedBEShifting          = true;
                vm.ApprovalPeriodList.NewVM.IsApprovedFixedAmountShifting = true;

                if (vm.CostBearer != null)
                {
                    vm.ApprovalPeriodList.NewVM.ServiceUnitName = vm.CostBearer.ServiceUnitName;
                }

            //}

            vm.ApprovalPeriodList.AddNewVMToList();
        }

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

        private void button_addTask_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTrigger.Validate(groupbox_newTask))
            {
                ViewModel.Tasks.AddNewVMToList();
            }
        }

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

        private void button_removeTask_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.Tasks.VMList.Remove(grid_tasks.GetCurrentValue<TaskVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_tasks);
        }

        private void button_remove_edit_employee_Click(object sender, RoutedEventArgs e)
        {
            var data = grid_tasks.View.FocusedRowData;

            if (data != null && data.RowHandle != null)
            {
                var vm = grid_tasks.GetRow(data.RowHandle.Value) as TaskVM;
                vm.Employees.Remove((CompactEmployeeDC)((Button)sender).Tag);
            }
        }

        private void button_remove_employee_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.Tasks.NewVM.Employees.Remove((CompactEmployeeDC)((Button)sender).Tag);
        }
        
        private void personsearchview_CostBearerContactPersonSelected(object sender, EventArgs<CompactPersonDC> e)
        {
            popup_person.IsOpen = false;
            personsearchview.ItemSelected -= personsearchview_CostBearerContactPersonSelected;

            var cbRelVM = tabcontrol_costbearers.SelectedItem as SupportConceptCostBearerRelVM;
            cbRelVM.CostBearerContactPerson = e.Data;
        }

        private void popupedit_costBearerContactPersonSearch_NewClick(object sender, RoutedEventArgs e)
        {
            VMFactory.CreatePersonVMAsync(
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<PersonVM, PersonDC, SupportConceptView>(cb, this, () => this.Dispatch(
                            delegate
                                {
                                    var newPerson = new CompactPersonDC();
                                    var newPersonOid = 0L;

                                    ServiceFacade.DoCustomerServiceSync(s => newPersonOid = s.InsertNewPerson(cb.CommitToDataContract()));

                                    ServiceFacade.DoCustomerServiceSync(s => newPerson = s.LoadPersonCompact(newPersonOid));

                                    ((SupportConceptCostBearerRelVM)tabcontrol_costbearers.SelectedItem)
                                        .CostBearerContactPerson = null;
                                    ((SupportConceptCostBearerRelVM)tabcontrol_costbearers.SelectedItem)
                                        .CostBearerContactPerson = newPerson;

                                    personsearchview.ObjectList.Add(newPerson);
                                }
                            ), personSavedOrUpdated: (s, args) => this.Dispatch(delegate { }))));
        }

        private void popupedit_costBearerContactPersonSearch_PopUpClick(object sender, RoutedEventArgs e)
        {
            personsearchview.ItemSelected += personsearchview_CostBearerContactPersonSelected;
            popup_person.IsOpen = true;
        }

        private void popupedit_costBearer_PopUpClick(object sender, RoutedEventArgs e)
        {
            // sccbrvm = (SupportConceptCostBearerRelVM)((Control)sender).Tag;
            // popup_costbearer.IsOpen = true;
        }

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

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

        private void tabitem_documents_Selected(object sender, RoutedEventArgs e)
        {
            if (ViewModel.IsNew)
            {
                MessageBox.Show(
                                "Bevor zu einem Datensatz Dokumente hinterlegt werden können, muss dieser gespeichert werden.", "Erst speichern bitte", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (tabitem_documents.Content == null)
            {
                tabitem_documents.Content = new BeWoFileView(TableID.SupportConcept, ViewModel.DataContract.SupportConceptOid.Value);
            }
        }

        // Kann das weg?
        private void ContextMenu_Click(object sender, RoutedEventArgs e)
        {
            //###IndServices
            //if (e.OriginalSource is MenuItem)
            //{
            //    var twi = e.OriginalSource as MenuItem;

            //    ServiceCategoryTreeItem selectedItem = this.treeview_individualServiceAccountings.SelectedItem as ServiceCategoryTreeItem;

            //    if (twi.Header.Equals("Neue Leistung"))
            //    {

            //        this.treeview_individualServiceAccountings.ItemContainerGenerator.StatusChanged +=
            //            this.ItemContainerGenerator_StatusChanged;

            //        ViewModel.AddIndividualService(selectedItem);

            //    }
            //    else if (twi.Header.Equals("Umbenennen"))
            //    {
            //        this.EditItem(this.treeview_individualServiceAccountings, null, selectedItem);
            //    }
            //    else if (twi.Header.Equals("Löschen"))
            //    {
            //        if (selectedItem != null && MessageBox.Show("ACHTUNG: Das Löschen von Leistungen kann nicht rückgängig gemacht werden.\n" +
            //                            "Alle verknüpften Eintragungen in der Zeiterfassung bleiben erhalten.\n\n" +
            //                            "Wollen Sie die Leistung '" + selectedItem.Name + "' wirklich löschen?", "Löschen bestätigen", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            //        {

            //            ViewModel.DeleteIndividualService(selectedItem);
            //        }
            //    }
            //}
        }

        private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            //###IndServices
            //var ig = (ItemContainerGenerator)sender;
            //if (ig.Status != GeneratorStatus.ContainersGenerated)
            //{
            //    return;
            //}

            //var n = ig.ContainerFromIndex(this.treeview_individualServiceAccountings.Items.Count - 1) as TreeViewItem;
            //if (n != null)
            //{
            //    n.IsSelected = true;

            //    new DispatcherTimer(
            //        TimeSpan.FromMilliseconds(200),
            //        DispatcherPriority.Background,
            //        (s1, e1) =>
            //            {
            //                ServiceCategoryTreeItem item = ig.ItemFromContainer(n) as ServiceCategoryTreeItem;
            //                this.EditItem(this.treeview_individualServiceAccountings, null, item);
            //                ((DispatcherTimer)s1).Stop();
            //        },
            //        this.Dispatcher).Start();
            //}
            //this.treeview_individualServiceAccountings.ItemContainerGenerator.StatusChanged -= this.ItemContainerGenerator_StatusChanged;
        }

        private void ContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            //if (e.OriginalSource is ContextMenu)
            //{
            //    ContextMenu menu = e.OriginalSource as ContextMenu;

            //    ServiceAccountingVM folder = this.treeview_individualServiceAccountings.SelectedItem as ServiceAccountingVM;

            //    foreach (var item in menu.Items)
            //    {
            //        if (item is MenuItem)
            //        {
            //            MenuItem menuitem = item as MenuItem;
            //            if (menuitem.Header.Equals("Umbenennen"))
            //                menuitem.IsEnabled = true;
            //        }
            //    }



            //}

        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                UpdateSelectedTreeItemText((TextBox)sender);
            }
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            UpdateSelectedTreeItemText((TextBox)sender);
        }

        private static void UpdateSelectedTreeItemText(TextBoxBase textBox)
        {
            if (!textBox.IsReadOnly)
            {
                textBox.Background = Brushes.Transparent;
                textBox.IsReadOnly = true;
                textBox.BorderThickness = new Thickness(0);
                textBox.Padding = new Thickness(1, 3, 1, 3);
            }
        }

        // scheint nicht mehr genutzt zu werden
        private void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var source = e.OriginalSource as DependencyObject;
            while (source != null && !(source is TreeViewItem))
            {
                source = VisualTreeHelper.GetParent(source);
            }

            if (source != null)
            {
                ((TreeViewItem)source).IsSelected = true;
                //this._SelectedTreeNode = (TreeViewItem)source;
            }
            else
            {
                //this._SelectedTreeNode = null;
            }
        }

        private void GoalTreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var source = e.OriginalSource as DependencyObject;
            while (source != null && !(source is TreeViewItem))
            {
                source = VisualTreeHelper.GetParent(source);
            }

            if (source != null)
            {
                ((TreeViewItem)source).IsSelected = true;
                _SelectedGoalTreeNode = (TreeViewItem)source;
            }
            else
            {
                _SelectedGoalTreeNode = null;
            }
        }

        private void ContextMenuGoals_Click(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is MenuItem)
            {
                var twi = e.OriginalSource as MenuItem;

                var selectedItem = treeview_Goals.SelectedItem as SupportConceptGoalTreeItem;

                if (twi.Header.Equals("Neues individuelles Ziel") || twi.Header.Equals("Neue individuelle Maßnahme"))
                {
					if (_SelectedGoalTreeNode != null)
					{
						_SelectedGoalTreeNode.ItemContainerGenerator.StatusChanged += GoalTreeItemContainerGenerator_StatusChanged;

                        ViewModel.AddZielOrMassnahme(selectedItem, twi.Header.Equals("Neues individuelles Ziel"));
					}
	                //EditItem(selectedItem);
                    //if (this._SelectedTreeNode != null)
                    //{
                    //    this._SelectedTreeNode.ItemContainerGenerator.StatusChanged +=
                    //        this.ItemContainerGenerator_StatusChanged;
                    //    this._SelectedTreeNode.IsExpanded = true;
                    //}
                }
                else if (twi.Header.Equals("Umbenennen"))
                {
                    EditItem(treeview_Goals, _SelectedGoalTreeNode, selectedItem);
                }
                else if (twi.Header.Equals("Löschen"))
                {
                    if (selectedItem != null)
                    {
                        var zielOderMassnahme = selectedItem.GoalEntryVM.Type == ValueListEntryType.SupportConceptGoalCategoryType || selectedItem.GoalEntryVM.Type == ValueListEntryType.SupportConceptIndividualGoalCategoryType ? "das Ziel" : "die Maßnahme";
                        var pluralendung = zielOderMassnahme.Equals("das Ziel") ? "en" : "n";

                        if (MessageBox.Show("ACHTUNG: Das Löschen von " + zielOderMassnahme.Substring(4) + pluralendung + " kann nicht rückgängig gemacht werden.\n" +
                                                                    "Alle verknüpften Eintragungen in der Zeiterfassung bleiben erhalten.\n\n" +
                                                                    "Wollen Sie " + zielOderMassnahme + " '" + selectedItem.ItemName + "' wirklich löschen?", "Löschen bestätigen", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {

                            //var p = ItemsControl.ItemsControlFromItemContainer(this._SelectedTreeNode) as TreeViewItem;
                            //p.IsSelected = true;
                            //var parent = this.treeview_individualServiceAccountings.SelectedItem as ServiceCategoryTreeItem;
                            //parent.Children.Remove(selectedItem);
                            ViewModel.DeleteIndividualGoal(selectedItem);
                        }
                    }
                }
            }
        }

        private static void EditItem(TreeView tv, TreeViewItem tvi, object item)
        {
            if (item != null)
            {
                var treeItem = tvi;
                if (treeItem == null && tv != null)
                    treeItem = tv.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

                if (treeItem != null)
                {
                    var textBox             = BeWoWpfUtils.FindVisualChild<TextBox>(treeItem);
                    textBox.IsReadOnly      = false;
                    textBox.Padding         = new Thickness(1, 1, 1, 1);
                    textBox.BorderThickness = new Thickness(1);
                    textBox.Background      = Brushes.White;
                    textBox.Tag             = tv.SelectedItem;

                    textBox.Focus();
                    textBox.SelectAll();
                }
            }
        }

        private void GoalTreeItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            var ig = (ItemContainerGenerator)sender;
            if (ig.Status != GeneratorStatus.ContainersGenerated)
            {
                return;
            }

            var n = ig.ContainerFromIndex(_SelectedGoalTreeNode.Items.Count - 1) as TreeViewItem;
            //var n = ig.ContainerFromIndex(this.treeview_individualGoals.Items.Count - 1) as TreeViewItem;
            if (n != null)
            {
                n.IsSelected = true;

                new DispatcherTimer(
                    TimeSpan.FromMilliseconds(200),
                    DispatcherPriority.Background,
                    (s1, e1) =>
                        {
                            _SelectedGoalTreeNode = n;
                            var item = ig.ItemFromContainer(n) as SupportConceptGoalDC;
                            EditItem(treeview_Goals, _SelectedGoalTreeNode, item);
                            ((DispatcherTimer)s1).Stop();
                        },

                    Dispatcher).Start();
            }

            _SelectedGoalTreeNode.ItemContainerGenerator.StatusChanged -= GoalTreeItemContainerGenerator_StatusChanged;
        }

        private void ContextMenuGoals_Opened(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is ContextMenu)
            {
                var menu = e.OriginalSource as ContextMenu;
                var goal = treeview_Goals.SelectedItem as SupportConceptGoalTreeItem;

                foreach (var menuitem in menu.Items.OfType<MenuItem>().Select(item => item))
                {
                    if (menuitem.Header.Equals("Umbenennen"))
                    {
                        menuitem.IsEnabled = goal != null && (goal.GoalType.Equals(ValueListEntryType.SupportConceptIndividualGoalCategoryType) || goal.GoalType.Equals(ValueListEntryType.SupportConceptIndividualGoalType));
                    }
                    else if (menuitem.Header.Equals("Neues individuelles Ziel") || menuitem.Header.Equals("Neue individuelle Maßnahme"))
                    {
                        menuitem.IsEnabled = goal != null && (goal.GoalType.Equals(ValueListEntryType.SupportConceptIndividualGoalCategoryType) || goal.GoalType.Equals(ValueListEntryType.SupportConceptGoalCategoryType));
                    }
                    else if (menuitem.Header.Equals("Löschen"))
                    {
                        menuitem.IsEnabled = goal != null && (goal.GoalType.Equals(ValueListEntryType.SupportConceptIndividualGoalCategoryType) || goal.GoalType.Equals(ValueListEntryType.SupportConceptIndividualGoalType));
                    }
                }
            }
        }

        #endregion

        private void CboServiceCategory_OnInitialized(object sender, EventArgs e)
        {
            var cbo = sender as ComboBoxEdit;

            if (cbo != null)
            {
                Cache.GetInstance().GetServiceCategoryDescriptionDict(
                    cb => cbo.Dispatch(delegate
                    {
                        cbo.ItemsSource = cb.Keys.Where(cat => cat.ScopeType == ScopeTypeId.Global).ToList();        
                    }));
            }
        }

        private void ButtonInfo_OnClick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            var bc  = btn.TemplatedParent as ButtonContainer;

            if (bc != null)
            {
                var bi = bc.Content as ButtonInfo;

                if (bi != null)
                {
                    var vm = bi.Tag as SupportConceptApprovalPeriodVM;

                    if (vm != null)
                    {
                        vm.ServiceCategory = null;
                    }
                }
            }
        }

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

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

        private void Popupedit_customer_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // CustomerView
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || ViewModel.Customer == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_View))
            {
                return;
            }

            VMFactory.CreateCustomerVMAsync(ViewModel.Customer.CustomerOid,
                cb => this.Dispatch(
                    () => BeWoUtils.OpenModalViewWindow<CustomerVM, CustomerDC, SupportConceptView>(cb, this, 
                    () => this.Dispatch(() => BeWoUtils.UpdateAllViews(ViewModel.Customer)))));
        }

        private void Popupedit_costBearerContactPersonSearch_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var contactPerson = ((SupportConceptCostBearerRelVM)tabcontrol_costbearers.SelectedItem).CostBearerContactPerson;

            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || contactPerson == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.PersonView_View))
            {
                return;
            }

            VMFactory.CreatePersonVMAsync(contactPerson.PersonOid,
                cb => this.Dispatch(
                    () => BeWoUtils.OpenModalViewWindow<PersonVM, PersonDC, SupportConceptView>(cb, this, 
                    () => this.Dispatch(() => BeWoUtils.UpdateAllViews(contactPerson)), personSavedOrUpdated: _PersonModalPopUp_PersonSavedOrUpdated)));
        }

        private void DoubleClickHandler(object sender, MouseButtonEventArgs e)
        {
            var selectedEmployee = ((ListBoxItem)sender).Content as CompactEmployeeDC;

            if (selectedEmployee == null || !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                return;
            }

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

        private void Control_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var label       = sender as Label;
            var labelparent = label.Parent as StackPanel;
            var btn         = labelparent.Children[0] as Button;
            var Employee    = btn.Tag as CompactEmployeeDC;

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

		private void ListItemGrid_OnLoaded(object sender, RoutedEventArgs e)
		{
			var grid = sender as Grid;

			var vm = grid.DataContext as SupportConceptApprovalPeriodVM;
		    
			if (vm != null && !SupportConceptApprovalPeriodVM.ShowContactCountFields)
			{
				grid.Children[grid.Children.Count - 2].Visibility = Visibility.Collapsed;
				grid.Children[grid.Children.Count - 3].Visibility = Visibility.Collapsed;
                grid.Children[grid.Children.Count - 4].Visibility = Visibility.Collapsed;
			    grid.Children[grid.Children.Count - 5].Visibility = Visibility.Collapsed;
			}
            
		    var gridControl = new GridControl();

            Grid.SetRow(gridControl, 7);
            Grid.SetColumn(gridControl, 0);
            Grid.SetColumnSpan(gridControl, 6);

		    gridControl.Margin = new Thickness(3d);

            var itemsSourceBinding = new Binding("SupportConceptApprovalEmployeeRelations.VMList") { Source = grid.DataContext };
		    gridControl.SetBinding(DataControlBase.ItemsSourceProperty, itemsSourceBinding);

            var gridControlVisibilityBinding = new Binding("SupportConceptApprovalEmployeeRelations.GridVisibility") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Source = grid.DataContext };
		    gridControl.SetBinding(VisibilityProperty, gridControlVisibilityBinding);

		    var deleteColumn = new GridColumn {Header = "", FixedWidth = true, Width = 24, ReadOnly = true, CellTemplate = (DataTemplate) Resources["DeleteBtnBetreuungsschluesselDataTemplate"]};

		    gridControl.Columns.Add(deleteColumn);

		    var employeeColumn = new GridColumn {Header = "Mitarbeiter", FieldName = "EmployeeString", AllowEditing = DefaultBoolean.False, Width = 250};

            var allowEditingBetreuungsschluesselColumn = BeWoApp.HasLoggedOnUserRight(new[] { UserRightType.EditAll, UserRightType.Betreuungsschluessel_Edit }) ? DefaultBoolean.True : DefaultBoolean.False;
            var betreuungsschluesselColumn = new GridColumn { Header = "Anteil an der Betreuung (%)", FieldName = "Betreuungsschluessel", AllowEditing = allowEditingBetreuungsschluesselColumn, Width = 170, EditSettings = new TextEditSettings { MaskUseAsDisplayFormat = true, MaskType = MaskType.Numeric, Mask = "########0.00" } };

            gridControl.Columns.Add(employeeColumn);
            gridControl.Columns.Add(betreuungsschluesselColumn);

		    gridControl.View = new TableView {AutoWidth = false, ShowGroupPanel = false, ShowGroupedColumns = false, ShowTotalSummary = false, NavigationStyle = GridViewNavigationStyle.Cell};


		    grid.Children.Add(gridControl);
		}

	    private void ChangeCostbearerBtn_Click(object sender, RoutedEventArgs e)
	    {
		    supportConceptCostBearerRel2Change = (SupportConceptCostBearerRelVM) ((Button) sender).Tag;
		    isChangingCostbearer               = true;

			popup_costbearer.IsOpen = true;
	    }

	    private void button_checkAllGoals_Click(object sender, RoutedEventArgs e)
	    {
		    CheckAllGoalTreeItems(true);
	    }

		private void button_uncheckAllGoals_Click(object sender, RoutedEventArgs e)
		{
			CheckAllGoalTreeItems(false);
		}

		private void CheckAllGoalTreeItems(bool check)
		{
			var allItems = treeview_Goals.ItemsSource as IList<SupportConceptGoalTreeItem>;

			foreach (var item in allItems)
			{
				item.IsChecked = check;
			}
		}

        

        private void button_openAddBetreuungsschluessel_Click(object sender, RoutedEventArgs e)
        {
            popup_newBetreuungsschluessel.IsOpen = true;

            var btn                  = (Button) sender;
            var grid                 = (Grid) btn.Parent;
            var border               = (Border) grid.Parent;
            var contentPresenter     = (ContentPresenter) border.TemplatedParent;
            SelectedApprovalPeriodVM = (SupportConceptApprovalPeriodVM)contentPresenter.Content;

			if (SelectedApprovalPeriodVM != null)
			{
				var alt = SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.VMList.Sum(s => s.Betreuungsschluessel);

				if (alt > 100)
					alt = 100;
				SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Betreuungsschluessel = 100 - alt;
			}
        }

        private void button_addBetreuungsschluessel_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedApprovalPeriodVM != null && Validate(groupbox_newBetreuungsschluessel))
            {
                var alt = SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.VMList.Sum(s => s.Betreuungsschluessel);

                if (alt + SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Betreuungsschluessel > 100)
                {
					MessageBox.Show("Die Summe der Anteile liegt bei über 100%. Hinzufügen nicht möglich.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.AddNewVMToList();
            }

            SelectedApprovalPeriodVM = null;

            popup_newBetreuungsschluessel.IsOpen = false;
        }

        private void button_cancelBetreuungsschluessel_Click(object sender, RoutedEventArgs e)
        {
            popup_newBetreuungsschluessel.IsOpen = false;
            SelectedApprovalPeriodVM = null;
        }

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

        private void Popupedit_betreuungsschluessel_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || 
                SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Employee == null || 
                !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                return;
            }

            VMFactory.CreateEmployeeVMAsync(SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Employee.EmployeeOid,
                cb => this.Dispatch(
                    () => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, SupportConceptView>(cb, this,
                    () => this.Dispatch(() => BeWoUtils.UpdateAllViews(SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Employee)))));
        }

        private void EmployeeSearchView_EmployeeSelected2(object sender, EventArgs<CompactEmployeeDC> e)
        {
            if (SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.VMList.Any(a => a.Employee.EmployeeOid.Equals(e.Data.EmployeeOid)))
            {
                MessageBox.Show("Sie können einen Betreuer nicht mehrmals hinzufügen.", "Ungültige Auswahl", MessageBoxButton.OK, MessageBoxImage.Warning);

                return;
            }

            popup_employee2.IsOpen = false;
            SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Employee = e.Data;
            popup_newBetreuungsschluessel.Focus();
        }

        public event PropertyChangedEventHandler PropertyChanged;

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

        private void DeleteBetreuungsschluesselButton_Click(object sender, RoutedEventArgs e)
        {
            var btn = (Button) sender;
            var currentObject = (SupportConceptApprovalPeriodEmployeeRelVM) ((EditGridCellData) btn.Tag).RowData.Row;

            var supportConceptCostBearerRel = ViewModel.CostBearerRelations.VMList.FirstOrDefault(f => f.ApprovalPeriodList.VMList.Any(a => a.SupportConceptApprovalEmployeeRelations.VMList.Contains(currentObject)));
            var approvalPeriod = supportConceptCostBearerRel.ApprovalPeriodList.VMList.FirstOrDefault(f => f.SupportConceptApprovalEmployeeRelations.VMList.Contains(currentObject));

            approvalPeriod.SupportConceptApprovalEmployeeRelations.VMList.Remove(currentObject);

            var abc = SelectedApprovalPeriodVM;
        }
    }

    public class ValueListEntryTypeToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var type = (ValueListEntryType) value;

            if (type.Equals(ValueListEntryType.SupportConceptIndividualGoalCategoryType) || type.Equals(ValueListEntryType.SupportConceptIndividualGoalType))
            {
                return new SolidColorBrush(Colors.SteelBlue);
            }

            return new SolidColorBrush(Colors.Black);
        }

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