using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Threading;

using BeWo.Core;
using BeWo.Core.Service;
using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.View.Controls;
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 DevExpress.Xpf.Docking;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Grid;

using Microsoft.Win32;

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

        private AdditionalServiceGroupOfPeopleView _AdditionalServiceGroupOfPeoplePopUp;

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

        private CompactEmployeeDC _SelectedEmployee;

        private ServiceRecordListVM _ViewModel;

        private readonly AssessmentSheetEntryView _AssessmentSheet;

	    private readonly Dictionary<long, CompactCustomerDC> _Oid2CustomerDict;

	    private readonly bool _disableTeilnehmerUpdate;

        public AdditionalServiceView(ServiceRecordListVM pViewModel, IEnumerable<CompactCustomerDC> allCustomerList)
        {
	        _disableTeilnehmerUpdate = true;
            InitializeComponent();

			AdditionalServiceBookings = new AdditionalServiceBookingListVM(new List<AdditionalServiceBookingDC>());

            MultiAddServGroupOfPeopleSelectionControl.EditGroupButtonClicked += multiAddServGroupOfPeopleSelectionControl_EditGroupButtonClicked;
            PopupContent.Visibility = Visibility.Hidden;
			_Oid2CustomerDict = new Dictionary<long, CompactCustomerDC>();
	        if (allCustomerList != null)
	        {
		        foreach (var cdc in allCustomerList)
		        {
			        _Oid2CustomerDict.Add(cdc.CustomerOid, cdc);
		        }
	        }

            ViewModel = pViewModel;
            ViewModel.ShowOnlyAdditionalServiceRecords = true;

            DownloadLinkEngine = new DownloadLinkEngine();
            LinkExcelExport.NavigateUri = DownloadLinkEngine.GenerateNewExcelLink();
            
            ComboboxServices.SelectionChanged += (s, e) =>
                {
                    if (ComboboxServices.SelectedIndex == -1)
                        ComboboxServices.SelectedIndex = 0;
                };

            InitDayCheckBoxes();

            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;
            }

            MultiEmployeeControlAddServ.SelectedEmployees.CollectionChanged += multiEmployeeAddServ_CollectionChanged;

            ReloadAdditionalServiceRelatedObjects();

            Years = new int[10];
            for (var i = (Years.Length - 1); i > -1; i--)
                Years[i] = DateTime.Now.Year - i;

            MonatsCombobox.DataContext = this;
            JahresCombobox.DataContext = this;
            TeilnahmeGrid.DataContext = this;

            SelectedYear = Years[0];
            SelectedMonth = (Monat) DateTime.Now.Month;
            
            MonatsCombobox.SelectedIndex = 0;
            JahresCombobox.SelectedIndex = 0;

            SaveBtn.IsEnabled = false;

			//SupportConceptSelectionControl.SupportConceptList = new List<CompactSupportConceptDC>();

            //this.Dispatch(() => Cache.GetInstance().GetAllActiveSupportConceptsCompact(x => this.Dispatch(() => { SupportConceptSelectionControl.SupportConceptList = x; })));
			ServiceFacade.DoEmployeeServiceSync(e => MultiEmployeeControlAddServ.SelectedEmployees.Add(e.LoadCompactEmployee(BeWoApp.LoggedOnEmployee.EmployeeOid.Value)));

	        _SelectedEmployee = MultiEmployeeControlAddServ.SelectedEmployees.First();

			_disableTeilnehmerUpdate = false;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        void multiEmployeeAddServ_CollectionChanged(object sender, EventArgs e)
        {
			AdditionalServiceBookings.NewVM.EmployeeOidList = MultiEmployeeControlAddServ.SelectedEmployees.Select(emp => emp.EmployeeOid).ToList();
			if (AdditionalServiceBookings.NewVM.EmployeeOidList.Count <= 0) 
                return;

			//_SelectedEmployee = AdditionalServiceBookings.NewVM.EmployeeOidList.First();
			//PopupeditEmployee.Text = _SelectedEmployee.ToString();
	        //_SelectedEmployee = null;
			//PopupeditEmployee.Text = AdditionalServiceBookings.NewVM.EmployeeOidList.First().ToString();
            
        }

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

        public List<AdditionalServiceDC> AdditionalServices { get; set; }
        public List<AdditionalServiceRegionDC> AdditionalServiceRegions { get; set; }

        public AdditionalServiceBookingListVM AdditionalServiceBookings { get; set; }
        public int GridColumnCount { get; set; }

        public int[] Years { get; set; }
        private int _SelectedYear;
        public int SelectedYear 
        {
            get { return _SelectedYear; }
            set
            {
                _SelectedYear = value;

                if ((int) SelectedMonth == 0)
                    return;

				ShouldGridBeSaved();
                GridColumnCount = DateTime.DaysInMonth(value, (int)SelectedMonth);
                UpdateTeilnahmeGrid();
            }
        }

        private Monat _SelectedMonth;
        public Monat SelectedMonth
        {
            get { return _SelectedMonth; }
            set
            {
				ShouldGridBeSaved();

                _SelectedMonth = value;
				GridColumnCount = DateTime.DaysInMonth(SelectedYear, (int)value);
                UpdateTeilnahmeGrid();
            }
        }

        private List<Teilnehmer> _TeilnehmerListe;
        public List<Teilnehmer> TeilnehmerListe
        {
            get
            {
                if(_TeilnehmerListe!=null)
                    _TeilnehmerListe.Sort((x, y) => x.Customer.LastNameFirstName.CompareTo(y.Customer.LastNameFirstName));

                return _TeilnehmerListe ?? (_TeilnehmerListe = new List<Teilnehmer>());
            } 
            set
            {
                _TeilnehmerListe = value; 
                OnPropertyChanged("TeilnehmerListe");
            }
        }

        private List<AdditionalServiceBookingVM> _SelectedBookings;
        public List<AdditionalServiceBookingVM> SelectedBookings
        {
            get { return _SelectedBookings; }
            set
            {
                _SelectedBookings = value; 
                OnPropertyChanged("SelectedBookings");
            }
        }

        internal void UpdateTeilnahmeGrid()
        {
	        if (!_disableTeilnehmerUpdate)
	        {
		        ReloadAdditionalServiceBookings();


		        if (Angebotscombobox.SelectedItem == null)
			        return;

		        SelectedBookings =
			        AdditionalServiceBookings.VMList.Where(
				        asb =>
					        asb.AdditionalServiceRegion.AdditionalServiceRegionOid.Equals(
						        (Angebotscombobox.SelectedItem as AdditionalServiceRegionDC).AdditionalServiceRegionOid) &&
					        asb.Date.Year == SelectedYear &&
					        asb.Date.Month == (int) SelectedMonth).ToList();

		        TeilnehmerListe = new List<Teilnehmer>();

		        foreach (var booking in SelectedBookings)
		        {
			        foreach (var teilnehmer in booking.CustomerOidDict)
			        {
				        if (teilnehmer.Key == 547)
				        {
					        int test = 0;
				        }
				        var bookingRel = new Dictionary<long, BookingRelationDictionaryValue>();
				        var index = -1;
				        var anwesenheiten = new bool[GridColumnCount];

				        if (TeilnehmerListe.Any(t => t.Customer.CustomerOid.Equals(teilnehmer.Key)))
				        {
					        var x = TeilnehmerListe.Where(t => t.Customer.CustomerOid.Equals(teilnehmer.Key)).ToList();
					        anwesenheiten = x.First().TeilnahmenForUpdating;
				        }

				        anwesenheiten[booking.Date.Day - 1] = teilnehmer.Value;

				        foreach (var item in TeilnehmerListe.Where(item => item.Customer.CustomerOid.Equals(teilnehmer.Key)))
				        {
					        index = TeilnehmerListe.IndexOf(item);
					        foreach (var element in item.BookingRelation.Where(element => !bookingRel.ContainsKey(element.Key)))
						        bookingRel.Add(element.Key, element.Value);
				        }

				        if (!bookingRel.ContainsKey(booking.DataContract.AdditionalServiceBookingOid.Value))
					        bookingRel.Add(booking.DataContract.AdditionalServiceBookingOid.Value,
						        new BookingRelationDictionaryValue(booking.Date, booking.StartDate.Value, booking.EndDate.Value));

				        if (index >= 0)
					        TeilnehmerListe.RemoveAt(index);

				        CompactCustomerDC customer = null;
				        if (_Oid2CustomerDict.ContainsKey(teilnehmer.Key))
				        {
					        customer = _Oid2CustomerDict[teilnehmer.Key];
				        }
				        if (customer == null)
				        {
					        customer = new CompactCustomerDC {CustomerOid = 0, FirstName = "Gelöscht"};
				        }
				        TeilnehmerListe.Add(new Teilnehmer(customer, anwesenheiten, bookingRel));

						var klienten = new Dictionary<long, bool>();
						foreach (var test2 in TeilnehmerListe)
						{
							if (!klienten.ContainsKey(test2.Customer.CustomerOid))
							{
								klienten.Add(test2.Customer.CustomerOid, true);
							}
							else
							{
								//Fehler
								int test = 0;
							}
						}
			        }
		        }

		        var monthInt = (int) SelectedMonth;
		        var daysInMonth = DateTime.DaysInMonth(SelectedYear, monthInt);
		        T28.Visible = daysInMonth >= 29;
		        T29.Visible = daysInMonth >= 30;
		        T30.Visible = daysInMonth == 31;

		        TeilnahmeGrid.ItemsSource = TeilnehmerListe;
		        TeilnahmeGrid.RefreshData();

		        foreach (var item in TeilnahmeGrid.Columns)
		        {
			        var swap = item.Header.ToString();
			        item.Header = "";
			        item.Header = swap;
		        }

		        UpdateAdditionalServiceReportUrl();
	        }
        }

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

        private void gridView1_DoubleClick(object sender, RoutedEventArgs e)
        {
            var selectedCustomer = ((sender as TableView).Grid.GetFocusedRow() as Teilnehmer).Customer;
            
            if(selectedCustomer != null)
                VMFactory.CreateCustomerVMAsync(selectedCustomer.CustomerOid, cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<CustomerVM, CustomerDC, AdditionalServiceView>(cb, this, () => this.Dispatch(
                        () => BeWoUtils.UpdateAllViews(selectedCustomer)))));
        }

        private void pg_ShownEditor(object sender, EditorEventArgs e)
        {
            if (!(e.Editor is CheckEdit)) 
                return;

            (e.Editor as CheckEdit).Tag = new CheckEditTag(e.Row as Teilnehmer, e.Column);
            (e.Editor as CheckEdit).Unchecked -= checked_changed;
            (e.Editor as CheckEdit).Unchecked += checked_changed;
            (e.Editor as CheckEdit).Checked -= checked_changed;
            (e.Editor as CheckEdit).Checked += checked_changed;
        }

		private void GridViewBase_OnHiddenEditor(object sender, EditorEventArgs e)
		{
			if (!(e.Editor is CheckEdit))
				return;

			(e.Editor as CheckEdit).Unchecked -= checked_changed;
			(e.Editor as CheckEdit).Checked -= checked_changed;
		}

        private readonly List<AdditionalServiceBookingDC> _BookingsToUpdate = new List<AdditionalServiceBookingDC>();
        private void checked_changed(object sender, RoutedEventArgs e)
        {
            var s = sender as CheckEdit;
            var tag = s.Tag as CheckEditTag;
            
            try
            {
	            var relationList =
		            tag.Teilnehmer.BookingRelation.Where(
			            b => b.Value.Datum.Equals(new DateTime(SelectedYear, (int) SelectedMonth, tag.GetHeaderAsDay())));

	            var keyList = relationList.Where(i => i.Key > 0 && i.Value.StartDate != DateTime.MinValue).Select(j => j.Key).ToList();

				//if (kvp.Key == 0 && kvp.Value.StartDate == DateTime.MinValue)
				//	return;
	            
                //key = kvp.Key;
	            if (relationList.Any())
	            {
		            var abList =
			            AdditionalServiceBookings.VMList.Where(asb => keyList.Contains(asb.DataContract.AdditionalServiceBookingOid.Value));

		            foreach (var ab in abList)
		            {
			            ab.CustomerOidDict[tag.Teilnehmer.Customer.CustomerOid] = s.IsChecked.Value;

			            if (!_BookingsToUpdate.Contains(ab.CommitToDataContract()))
				            _BookingsToUpdate.Add(ab.CommitToDataContract());

			            SaveBtn.IsEnabled = true;
		            }
	            }

            }
            catch (Exception) { return; }
        }

        private void SaveBookingChanges(object sender, RoutedEventArgs e)
        {
	       SaveGridChanges(true);
        }

	    private void SaveGridChanges(bool updateGrid)
	    {
		    Mouse.OverrideCursor = Cursors.Wait;
		    try
		    {
			    // do stuff

			    if (_BookingsToUpdate.Count == 0 && newShortAddAD.Any())
			    {
				    ServiceFacade.DoOperationsServiceSync(
					    o => o.InsertNewAdditionalServiceBookings(new List<AdditionalServiceBookingDC>(newShortAddAD)));

			    }
			    else if (_BookingsToUpdate.Any() && !newShortAddAD.Any())
			    {
				    ServiceFacade.DoOperationsServiceSync(o => o.UpdateAdditionalServiceBookings(_BookingsToUpdate));
			    }
			    else if (_BookingsToUpdate.Any() && newShortAddAD.Any())
			    {
				    ServiceFacade.DoOperationsServiceSync(o => o.UpdateAdditionalServiceBookings(_BookingsToUpdate));
				    ServiceFacade.DoOperationsServiceSync(
					    o => o.InsertNewAdditionalServiceBookings(new List<AdditionalServiceBookingDC>(newShortAddAD)));
			    }
			    if (updateGrid)
				    UpdateTeilnahmeGrid();
			    SaveBtn.IsEnabled = false;
		    }
		    finally
		    {
			    Mouse.OverrideCursor = null;
		    }
	    }

        public DownloadLinkEngine DownloadLinkEngine { get; set; }

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

        public override string Title
        {
            get { return "Ergänzende Dienste"; }
        }

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

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

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

        private ServiceRecordListVM ViewModel
        {
            get { return _ViewModel; }

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

                DataContext = value;

                _ViewModel = value;
                
                _ViewModel.ServiceRecordListChanged += _ViewModel_ServiceRecordListChanged;

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

        public void AnimateOpacity(double pOpacitiy, double pDuration)
        {
            var lAnimation = new DoubleAnimation
                {From = DetailContentGrid.Opacity, To = pOpacitiy, Duration = TimeSpan.FromMilliseconds(pDuration)};

            DetailContentGrid.BeginAnimation(OpacityProperty, 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)
            {
                if (vm.GroupOid != null)
                {
                    List<ServiceRecordVM> deletedVMs = ViewModel.VMList.Where(item => item.GroupOid != null && item.GroupOid.Value == vm.GroupOid.Value).ToList();

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

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

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

        public void SetSelectedServiceRecordVM(ServiceRecordVM vm)
        {
            SrListBox.SelectedItem = vm;
        }

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

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

							int idx = 0;
							foreach (ServiceRecordVM 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();
		}
		
        private void ReloadAdditionalServiceRelatedObjects()
        {
            AdditionalServices = ServiceFacade.DoOperationsServiceSync(f => f.GetAllAdditionalService());
            AdditionalServiceRegions = ServiceFacade.DoOperationsServiceSync(adsr => adsr.GetAllAdditionalServiceRegion());

            GroupBoxAdditionalService.DataContext = this;
        }

	    private void ReloadAdditionalServiceBookings()
	    {
			if (newShortAddAD != null)
				newShortAddAD.Clear();
			if (_BookingsToUpdate != null)
				_BookingsToUpdate.Clear();

			var start = new DateTime(SelectedYear, (int)SelectedMonth, 1);
		    var end = start.AddMonths(1);

			AdditionalServiceBookings.VMList.Clear();

		    long? regionOid = null;

		    if (AdditionalServiceBookings.NewVM.AdditionalServiceRegion != null)
		    {
		        regionOid = AdditionalServiceBookings.NewVM.AdditionalServiceRegion.AdditionalServiceRegionOid;
		    }

			foreach (var item in ServiceFacade.DoOperationsServiceSync(t => t.GetAllAdditionalServiceBookings(regionOid, start, end)))
			{
			    AdditionalServiceBookings.VMList.Add(new AdditionalServiceBookingVM(item));
			}

		    AdditionalServiceBookings.NewVM.AdditionalServiceRegion = (AdditionalServiceRegionDC)Angebotscombobox.SelectedItem;
	    }

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

        private void Edit(ServiceRecordVM vm)
        {
            if (vm != null && vm.EditAllowed)
            {
                BeWoView serviceRecordEditView;
                double height = 450;
                const double width = 800;
                if (vm.GroupOid != null)
                {
                    serviceRecordEditView = new ServiceRecordGroupEditView();
                }
                else
                {
                    serviceRecordEditView = new ServiceRecordEditView();
                }

                PopupContent.Child = serviceRecordEditView;
                PopupContent.Width = width;

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

                PopupContent.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)
                                {
                                    serviceRecordEditView.SaveData();
                                    ClosePopupView();

                                    if (serviceRecordEditView is ServiceRecordEditView)
                                    {
                                        vm.Employee = _SelectedEmployee;

                                        ViewModel.RefreshServiceRecordsForSelectedTreeNode();
                                        SetSelectedServiceRecordVM(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;
                                    SetPopupViewVisible(true);
                                }));
                }
            }
        }

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

            ViewModel.SelectedEmployee = _SelectedEmployee;

            if (WithoutClient)
                SelectedItemChanged(null);
        }

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

                var childOfChild = FindVisualChild<TChildItem>(child);
                if (childOfChild != null)
                    return childOfChild;
            }

            return 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;
                WrapPanelDays.Visibility = Visibility.Collapsed;
                WrapPanelDays.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(BaseEdit.EditValueProperty, typeof (DateEdit)).AddValueChanged(
                DatepickerNewDate,
                (s, e) => _DayBoxes.DoForEach(
                    iCheck =>
                        {
                            iCheck.Value.IsChecked = DatepickerNewDate.EditValue != null &&
                                                     iCheck.Key == DatepickerNewDate.DateTime.DayOfWeek;
                            iCheck.Value.IsHitTestVisible = !iCheck.Value.IsChecked.Value;
                            iCheck.Value.IsEnabled = iCheck.Value.IsHitTestVisible;
                        }));
        }

		private void GridViewBase_OnCellValueChanging(object sender, CellValueChangedEventArgs e)
		{
			// Das Datum ist der eindeutige Identifikator
			var tableView = (TableView)sender;
			var spalten = (List<Teilnehmer>) tableView.Grid.ItemsSource;
			var alleTeilnehmer = spalten.Select(s => s.Customer);

			var ausgewaehlterTeilnehmer = (Teilnehmer) e.Row;
			var ausgewaehlterTag = Convert.ToInt32(e.Column.Header.ToString().Split('.')[0]);
			var ausgewaehltesDatum = new DateTime(SelectedYear, (int)_SelectedMonth, ausgewaehlterTag);

			var existiert = ausgewaehlterTeilnehmer.BookingRelation.Any(br => br.Value.Datum.Equals(ausgewaehltesDatum));
			if (existiert) return;

			if (_SelectedBookings.Any(vm => vm.Date.Equals(ausgewaehltesDatum)))
			{
				var btu = _SelectedBookings.First(vm => vm.Date.Equals(ausgewaehltesDatum));
				if (btu.CustomerOidDict.ContainsKey(ausgewaehlterTeilnehmer.Customer.CustomerOid))
					btu.CustomerOidDict.Remove(ausgewaehlterTeilnehmer.Customer.CustomerOid);
				btu.CustomerOidDict.Add(ausgewaehlterTeilnehmer.Customer.CustomerOid, Convert.ToBoolean(e.Value));
				_BookingsToUpdate.Add(btu.CommitToDataContract());
				SaveBtn.IsEnabled = true;
				return;
			}

			if (newShortAddAD.Any(ad => ad.Date.Equals(ausgewaehltesDatum)))
			{
				newShortAddAD.First(ad => ad.Date.Equals(ausgewaehltesDatum)).CustomerOidDict[ausgewaehlterTeilnehmer.Customer.CustomerOid] = Convert.ToBoolean(e.Value);
				return;
			}

			var mitarbeiter = MultiEmployeeControlAddServ.SelectedEmployees.Select(emp => emp.EmployeeOid).ToList();
			var temp = alleTeilnehmer.ToList();

			
			//Dictionary<long, bool> klienten = new Dictionary<long, bool>();
			//foreach (var customer in alleTeilnehmer)
			//{
			//	if (!klienten.ContainsKey(customer.CustomerOid))
			//	{
			//		klienten.Add(customer.CustomerOid, customer.Equals(ausgewaehlterTeilnehmer.Customer) && Convert.ToBoolean(e.Value));
			//	}
			//	else
			//	{
			//		//Fehler
			//		//int test = 0;
			//	}
			//}
			var klienten = alleTeilnehmer.ToDictionary(teilnehmer => teilnehmer.CustomerOid, teilnehmer => (teilnehmer.Equals(ausgewaehlterTeilnehmer.Customer) && Convert.ToBoolean(e.Value)));
			var bereich = (AdditionalServiceRegionDC) Angebotscombobox.SelectedItem;
			var neueBuchung = new AdditionalServiceBookingDC 
			{
				AdditionalServiceRegion = bereich, 
				CustomerOidDict = klienten, 
				EmployeeOidList = mitarbeiter,
				Date = ausgewaehltesDatum,
				StartDate = ausgewaehltesDatum,
				EndDate = ausgewaehltesDatum.AddHours(23).AddMinutes(59).AddSeconds(59)
			};

			if(neueBuchung.EndDate.HasValue && neueBuchung.StartDate.HasValue)
			{
				var roundedDuration = Convert.ToDecimal((neueBuchung.EndDate.Value - neueBuchung.StartDate.Value).GetTotalMinutes());
				neueBuchung.RoundedDuration = roundedDuration;
			}

			newShortAddAD.Add(neueBuchung);

			SaveBtn.IsEnabled = true;
		}

		private readonly List<AdditionalServiceBookingDC> newShortAddAD = new List<AdditionalServiceBookingDC>(); 

        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;
            if (ViewModel.PrototypeVM.GoalTree != null && ViewModel.PrototypeVM.GoalTree.Count > 0)
                foreach (var child in from item in ViewModel.PrototypeVM.GoalTree from child in item.Children where child.IsChecked select child)
                    child.IsChecked = false;
        }

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

                ViewModel.ChangeTreeItemSelection(selectedNode);
                SrListBox.SelectedIndex = -1;

                var sv = FindVisualChild<ScrollViewer>(SrListBox);
                if (sv != null)
                    sv.ScrollToTop();

                UpdateServiceRecordListReportUrl(selectedNode);
            }
        }

        private void SetPopupViewVisible(bool visible)
        {
            PopupContent.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;
                }
            }


            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 bool ValidateAdditionalServiceBookings()
        {
            const bool lValid = true;

            if (AdditionalServiceBookings.NewVM.CustomerOidDict.Count == 0)
            {
                MessageBox.Show("Bitte wählen Sie mindestens einen Klienten aus, für den dieses Angebot gebucht werden soll.", 
                                "Buchen nicht möglich", 
                                MessageBoxButton.OK, 
                                MessageBoxImage.Information);
                return false;
            }

            if (AdditionalServiceBookings.NewVM.EmployeeOidList.Count == 0)
            {
                MessageBox.Show("Bitte wählen Sie mindestens einen Mitarbeiter aus, für den dieses Angebot gebucht werden soll.", 
                                "Buchen nicht möglich", 
                                MessageBoxButton.OK, 
                                MessageBoxImage.Information);
                return false;
            }

            var customerOids = new List<long>();

            AdditionalServiceBookings.NewVM.CustomerOidDict.Keys.DoForEach(c => customerOids.Add(c));

            if (ServiceFacade.DoOperationsServiceSync(b =>
                b.OverlapsWithAnotherAdditionalServiceBooking(
                    AdditionalServiceBookings.NewVM.AdditionalServiceRegion.AdditionalServiceRegionOid.Value, customerOids,
                    AdditionalServiceBookings.NewVM.Date)))
            {
                if (MessageBox.Show(
                        "An dem ausgewählten Tag existiert bereits eine Buchung. Möchten Sie trotzdem buchen?",
                        "Buchen", MessageBoxButton.YesNo, MessageBoxImage.Information).Equals(MessageBoxResult.No))
                {
                    return false;
                }
            }

            return lValid;
        }


        private void _ViewModel_ServiceRecordListChanged(object sender, EventArgs e)
        {
            var list = _ViewModel.ServiceRecordsForSelectedCustomer.OrderByDescending(srVM => srVM.DateAndTime).ToList();
            
            SrListBox.ItemsSource = 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;

            Edit(GetSelectedServiceRecordFromListBox());
        }

        private void button_ADadd_Click(object sender, RoutedEventArgs e)
        {
            if (AdditionalServiceBookings.NewVM == null ||
                AdditionalServiceBookings.NewVM.CustomerOidDict == null) 
                return;

			var mitarbeiter = MultiEmployeeControlAddServ.SelectedEmployees;
			var klienten = MultiAddServGroupOfPeopleSelectionControl.CurrentGroup.CustomerList;

            //ReloadAdditionalServiceRelatedObjects();

            if (!ValidateAdditionalServiceBookings())
                return;

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

            AdditionalServiceBookings.AddNewVMToList();

            if (AdditionalServiceBookings.AddedCount > 0)
            {
                lToDos.Add(
                    s =>
                        {
                            var newItems = AdditionalServiceBookings.CommitAdded();
                            try
                            {
                                var oids = s.InsertNewAdditionalServiceBookings(newItems);

                                var idx = 0;
                                foreach (var vm in AdditionalServiceBookings.VMList.Where(vm => vm.IsNew))
                                {
                                    vm.IsNew = false;
                                    vm.DataContract.AdditionalServiceBookingVersion = 1;
                                    vm.DataContract.AdditionalServiceBookingOid = oids[idx++];
                                }
                            }
                            catch (Exception)
                            {
                                var newVMs = AdditionalServiceBookings.VMList.Where(vm => vm.IsNew).ToList();

                                foreach (var additionalServiceBookingVM in newVMs)
                                    AdditionalServiceBookings.VMList.Remove(additionalServiceBookingVM);

                                throw;
                            }
                        });
            }
            
            ServiceFacade.DoMultipleOperationsServicesAsync(lToDos, () =>
                {
                    //AdditionalServiceBookings.VMList.Clear();

                    //foreach (var item in ServiceFacade.DoOperationsServiceSync(t => t.GetAllAdditionalServiceBookings()))
                    //    AdditionalServiceBookings.VMList.Add(new AdditionalServiceBookingVM(item));

	                AdditionalServiceBookings.NewVM.EmployeeOidList =
		                MultiEmployeeControlAddServ.SelectedEmployees.Select(emp => emp.EmployeeOid).ToList();
                    this.Dispatch(
						delegate 
						{ 
							AdditionalServiceBookings.NewVM.CustomerOidDict = MultiAddServGroupOfPeopleSelectionControl.CurrentGroup.CustomerList.ToDictionary(customer => customer.CustomerOid, customer => true);
                            UpdateAngebotsCombobox();
							UpdateTeilnahmeGrid();
						});
                });
        }

        private void BereichsComboboxChange(object sender, RoutedEventArgs e)
        {
            Bereichscombobox.DataContext = this;

            if (Bereichscombobox.SelectedItem == null)
                Bereichscombobox.SelectedItem = AdditionalServices.ElementAt(0);

            UpdateAngebotsCombobox();
        }

        private void UpdateAngebotsCombobox()
        {
            var ASRDCs = AdditionalServiceRegions.Where( id => id.AdditionalServiceOid == ((AdditionalServiceDC) Bereichscombobox.SelectedItem).AdditionalServiceOid).ToList();

			var gleich = false;
	        var liste =  Angebotscombobox.ItemsSource as List<AdditionalServiceRegionDC>;

			if(Angebotscombobox.ItemsSource != null && (liste.Count == ASRDCs.Count))
				for (int i = 0; i < ASRDCs.Count; i++)
					gleich = liste[i].Equals(ASRDCs[i]);

			if (Angebotscombobox.ItemsSource == null || !gleich)
				Angebotscombobox.ItemsSource = ASRDCs;

            if (ASRDCs.Any() && Angebotscombobox.SelectedItem == null)
                Angebotscombobox.SelectedItem = AdditionalServiceRegions.Where(id => id.AdditionalServiceOid == ((AdditionalServiceDC) Bereichscombobox.SelectedItem).AdditionalServiceOid).ElementAt(0);

            if (Angebotscombobox.SelectedItem != null)
                AdditionalServiceBookings.NewVM.AdditionalServiceRegion = (AdditionalServiceRegionDC)Angebotscombobox.SelectedItem;
        }

        private void AngebotsComboboxChange(object sender, RoutedEventArgs e)
        {

	        //SelectionChangedEventArgs args = e as SelectionChangedEventArgs;
	        //var added = args.AddedItems;
	        //var removed = args.RemovedItems;

	        ShouldGridBeSaved();

            if (Angebotscombobox.SelectedItem == null)
                return;

            AdditionalServiceBookings.NewVM.AdditionalServiceRegion = (AdditionalServiceRegionDC)Angebotscombobox.SelectedItem;
            
			UpdateTeilnahmeGrid();
        }

		private bool ShouldGridBeSaved()
		{
			if (IsGridDirty())
			{
				//var ret = MessageBox.Show("Wollen Sie die Änderungen speichern?", "Änderungen speichern",
				//	MessageBoxButton.YesNo, MessageBoxImage.Question);

				//if (ret == MessageBoxResult.No)
				//	return false;

				SaveGridChanges(false);
				return true;
			}
			return false;
		}

		private bool IsGridDirty()
		{
			return _BookingsToUpdate.Count > 0 || newShortAddAD.Any();
		}

        private void button_add_Click(object sender, RoutedEventArgs e)
        {
			var lValid = ValidationTrigger.Validate(root);

			if (lValid)
			{
				lValid = SaveSingleBooking();

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

			//var lValid = ValidationTrigger.Validate(root);
			//var records = new List<ServiceRecordDC>();

			//foreach (ServiceRecordVM iVM in ViewModel.CreateFromPrototype())
			//{
			//	if (iVM.Customer == null)
			//		break;

			//	iVM.Employee = _SelectedEmployee;
			//	records.Add(iVM.CommitToDataContract());
			//}

			//if (lValid)
			//	SaveSingleBooking();
			//else
			//	foreach (var iVM in ViewModel.CreateFromPrototype())
			//		MessageBox.Show("Der gewählte Zeitpunkt '" + iVM.DateAndTime.Value.ToShortDateString() + " " + iVM.DateAndTime.Value.ToShortTimeString() + "' überschneidet sich mit einem bereits existierenden Eintrag desselben Hilfeplans.\nSpeichern nicht möglich.", "Speichern nicht möglich", MessageBoxButton.OK, MessageBoxImage.Information);
        }

		
		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, false, 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 linkExcelExport_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            var list = SrListBox.ItemsSource as List<ServiceRecordVM>;
            var lHeaderCaptions = new List<string>();
            var lContent = new List<List<string>>();

            lHeaderCaptions.Add("Datum");
            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");
            lHeaderCaptions.Add("Dokumentation");

            if (list != null)
            {
                lContent.AddRange(list.Select(vm => new List<string> {String.Format("{0:d}", (vm.StartTime != null && vm.StartTime.Value.Second == 0 ? vm.DateAndTime : vm.Date)), 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}));
            }

			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 popupedit_employee_PopUpClick(object sender, RoutedEventArgs e)
        {
            PopupEmployee.IsOpen = true;
        }

        private void serviceRecordListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!IsPartOf(e.OriginalSource, typeof(ScrollBar)))
                Edit(GetSelectedServiceRecordFromListBox());
        }

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

                HideAssessmentSheet();
        }

        private DockLayoutManager dockLayoutManager;
        private Grid panel1;
        private Grid panel2;
        private Grid panel3;

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

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


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

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

            GroupBoxNeueLeistung.Content = GridNeueLeistung;
            FLSGrid.Children.Add(GroupBoxNeueLeistung);
            FLSGrid.Children.Add(ServiceRecordListContent);
            FLSGrid.Children.Add(TxtServiceListCount);
            FLSGrid.Children.Add(StackPanelInfoText);
            FLSGrid.Children.Add(PunktebogenRootGrid);
        }

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

        public override void ModalPopUpSaveInvoked()
        {
        }

        void multiAddServGroupOfPeopleSelectionControl_EditGroupButtonClicked(object sender, EventArgs e)
        {
            OpenAddServGroupEditView();
        }

        private void OpenAddServGroupEditView()
        {
            VMFactory.CreateAdditinoalServiceGroupOfPeopleListVMAsync(
                    cb => this.Dispatch(delegate
                        {
                            _AdditionalServiceGroupOfPeoplePopUp = new AdditionalServiceGroupOfPeopleView(cb)
                                {
                                    MinWidth = 700,
                                    MaxWidth = 700,
                                    Height = 600
                                };

                            _AdditionalServiceGroupOfPeoplePopUp.GroupOfPeopleSavedOrUpdated += AdditionalServiceGroupOfPeoplePopUp_AdditionalServiceGroupOfPeopleSavedOrUpdated;
                            BeWoApp.MainControl.ShowControlAsModalPopUp(_AdditionalServiceGroupOfPeoplePopUp);
                            _AdditionalServiceGroupOfPeoplePopUp.Focus();
                        })
                );
        }

        private void LinkPdfExport_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            BeWoUtils.NavigateToReportUri(((Hyperlink)sender).NavigateUri.ToString(), "Druckvorschau");
        }

        private static void AdditionalServiceGroupOfPeoplePopUp_AdditionalServiceGroupOfPeopleSavedOrUpdated(object sender, EventArgs<AdditionalServiceGroupOfPeopleListVM> e)
        {
            BeWoApp.MainControl.CloseCurrentPopUp();
        }

        private void MultiAddServGroupOfPeopleSelectionControl_OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var groupSearchControl = (MultiAddServGroupOfPeopleSelectionControl) sender;
            AdditionalServiceBookings.NewVM.CustomerOidDict = groupSearchControl.CurrentGroup.CustomerList.ToDictionary(customer => customer.CustomerOid, customer => true);

            this.Dispatch(() => Cache.GetInstance().GetAllActiveSupportConceptsCompact(x => this.Dispatch(() => { SupportConceptSelectionControl.SupportConceptList = x; })));
        }

        private void UpdateAdditionalServiceReportUrl()
        {
            var url = BeWoApp.SiteOfOrigin + "/ReportView.aspx" + "?y=" + SelectedYear + "&m=" + SelectedMonth + "&asroid=" + (Angebotscombobox.SelectedItem as AdditionalServiceRegionDC).AdditionalServiceRegionOid + "&type=" + Utils.EnumName(ReportTypes.AdditionalServiceBookingReport);
            url = BeWoWpfUtils.GetHTMLEncodedURL(url);

            LinkPdfExport2.NavigateUri = new Uri(url);
        }

        private void FLSAnlegenBtn_OnClick(object sender, RoutedEventArgs e)
        {
            if (TeilnahmeGrid.Visibility == Visibility.Visible)
            {
                TeilnahmeGrid.Visibility = Visibility.Collapsed;
                MonatsLabel.Visibility = Visibility.Collapsed;
                MonatsCombobox.Visibility = Visibility.Collapsed;
                JahresLabel.Visibility = Visibility.Collapsed;
                JahresCombobox.Visibility = Visibility.Collapsed;
                SaveBtn.Visibility = Visibility.Collapsed;
                TextblockLinkPdfexport2.Visibility = Visibility.Collapsed;

                FLSInfoGrid.Visibility = Visibility.Visible;
				button_ADadd.Visibility = Visibility.Hidden;
            }
            else
            {
                TeilnahmeGrid.Visibility = Visibility.Visible;
                MonatsLabel.Visibility = Visibility.Visible;
                MonatsCombobox.Visibility = Visibility.Visible;
                JahresLabel.Visibility = Visibility.Visible;
                JahresCombobox.Visibility = Visibility.Visible;
                SaveBtn.Visibility = Visibility.Visible;
                TextblockLinkPdfexport2.Visibility = Visibility.Visible;
				button_ADadd.Visibility = Visibility.Visible;

                FLSInfoGrid.Visibility = Visibility.Collapsed;

                if (AdditionalServiceBookings.NewVM.EmployeeOidList.Count > 0)
                {
                    //_SelectedEmployee = AdditionalServiceBookings.NewVM.EmployeeOidList.First();
                   // PopupeditEmployee.Text = _SelectedEmployee.ToString();
					//_SelectedEmployee = null;
					//PopupeditEmployee.Text = AdditionalServiceBookings.NewVM.EmployeeOidList.First().ToString();
                }
            }

            FLSGrid.Visibility = FLSGrid.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
        }

        private void supportConceptSelectionControl_ItemSelected(object sender, EventArgs<FlatSupportConceptTreeNodeDC> e)
        {
            ViewModel.ChangeTreeItemSelection(e.Data);
            ViewModel.RefreshServiceRecordsForSelectedTreeNode();
            UpdateServiceRecordListReportUrl(e.Data);

            ComboBoxTreeViewControl.ResetControl();

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

            ComboBoxTreeViewControl.TreeViewSourceList = ViewModel.PrototypeVM.GoalTree;
        }

        private void LinkPdfExport2_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            BeWoUtils.NavigateToReportUri(((Hyperlink)sender).NavigateUri.ToString(), "Druckvorschau");
        }
    }

    public class Teilnehmer
    {
        public CompactCustomerDC Customer { get; set; }

        #region Anwesenheiten
        private bool _t0; public bool t0 { get { return _t0; } set { _t0 = value; TeilnahmenForUpdating[0] = value; } }
        private bool _t1; public bool t1 { get { return _t1; } set { _t1 = value; TeilnahmenForUpdating[1] = value; } }
        private bool _t2; public bool t2 { get { return _t2; } set { _t2 = value; TeilnahmenForUpdating[2] = value; } }
        private bool _t3; public bool t3 { get { return _t3; } set { _t3 = value; TeilnahmenForUpdating[3] = value; } }
        private bool _t4; public bool t4 { get { return _t4; } set { _t4 = value; TeilnahmenForUpdating[4] = value; } }
        private bool _t5; public bool t5 { get { return _t5; } set { _t5 = value; TeilnahmenForUpdating[5] = value; } }
        private bool _t6; public bool t6 { get { return _t6; } set { _t6 = value; TeilnahmenForUpdating[6] = value; } }
        private bool _t7; public bool t7 { get { return _t7; } set { _t7 = value; TeilnahmenForUpdating[7] = value; } }
        private bool _t8; public bool t8 { get { return _t8; } set { _t8 = value; TeilnahmenForUpdating[8] = value; } }
        private bool _t9; public bool t9 { get { return _t9; } set { _t9 = value; TeilnahmenForUpdating[9] = value; } }

        private bool _t10; public bool t10 { get { return _t10; } set { _t10 = value; TeilnahmenForUpdating[10] = value; } }
        private bool _t11; public bool t11 { get { return _t11; } set { _t11 = value; TeilnahmenForUpdating[11] = value; } }
        private bool _t12; public bool t12 { get { return _t12; } set { _t12 = value; TeilnahmenForUpdating[12] = value; } }
        private bool _t13; public bool t13 { get { return _t13; } set { _t13 = value; TeilnahmenForUpdating[13] = value; } }
        private bool _t14; public bool t14 { get { return _t14; } set { _t14 = value; TeilnahmenForUpdating[14] = value; } }
        private bool _t15; public bool t15 { get { return _t15; } set { _t15 = value; TeilnahmenForUpdating[15] = value; } }
        private bool _t16; public bool t16 { get { return _t16; } set { _t16 = value; TeilnahmenForUpdating[16] = value; } }
        private bool _t17; public bool t17 { get { return _t17; } set { _t17 = value; TeilnahmenForUpdating[17] = value; } }
        private bool _t18; public bool t18 { get { return _t18; } set { _t18 = value; TeilnahmenForUpdating[18] = value; } }
        private bool _t19; public bool t19 { get { return _t19; } set { _t19 = value; TeilnahmenForUpdating[19] = value; } }

        private bool _t20; public bool t20 { get { return _t20; } set { _t20 = value; TeilnahmenForUpdating[20] = value; } }
        private bool _t21; public bool t21 { get { return _t21; } set { _t21 = value; TeilnahmenForUpdating[21] = value; } }
        private bool _t22; public bool t22 { get { return _t22; } set { _t22 = value; TeilnahmenForUpdating[22] = value; } }
        private bool _t23; public bool t23 { get { return _t23; } set { _t23 = value; TeilnahmenForUpdating[23] = value; } }
        private bool _t24; public bool t24 { get { return _t24; } set { _t24 = value; TeilnahmenForUpdating[24] = value; } }
        private bool _t25; public bool t25 { get { return _t25; } set { _t25 = value; TeilnahmenForUpdating[25] = value; } }
        private bool _t26; public bool t26 { get { return _t26; } set { _t26 = value; TeilnahmenForUpdating[26] = value; } }
        private bool _t27; public bool t27 { get { return _t27; } set { _t27 = value; TeilnahmenForUpdating[27] = value; } }
        private bool _t28; public bool t28 { get { return _t28; } set { _t28 = value; TeilnahmenForUpdating[28] = value; } }
        private bool _t29; public bool t29 { get { return _t29; } set { _t29 = value; TeilnahmenForUpdating[29] = value; } }

        private bool _t30; public bool t30 { get { return _t30; } set { _t30 = value; TeilnahmenForUpdating[30] = value; } }
        #endregion

        public Dictionary<long, BookingRelationDictionaryValue> BookingRelation { get; set; }
        public bool[] TeilnahmenForUpdating { get; set; }

        public bool ContainsOneRelationOnly { get; set; }

        public Teilnehmer(CompactCustomerDC customer, IList<bool> teilnahmen, Dictionary<long, BookingRelationDictionaryValue> bookingRelation, bool containsOneRelationOnly = false)
        {
            Customer = customer;

            ContainsOneRelationOnly = containsOneRelationOnly;

            if (BookingRelation == null)
                BookingRelation = new Dictionary<long, BookingRelationDictionaryValue>();

            BookingRelation = BookingRelation.Union(bookingRelation).ToDictionary(k => k.Key, v => v.Value);
            TeilnahmenForUpdating = teilnahmen.ToArray();

            t0 = teilnahmen[0];
            t1 = teilnahmen[1];
            t2 = teilnahmen[2];
            t3 = teilnahmen[3];
            t4 = teilnahmen[4];
            t5 = teilnahmen[5];
            t6 = teilnahmen[6];
            t7 = teilnahmen[7];
            t8 = teilnahmen[8];
            t9 = teilnahmen[9];
            t10 = teilnahmen[10];
            t11 = teilnahmen[11];
            t12 = teilnahmen[12];
            t13 = teilnahmen[13];
            t14 = teilnahmen[14];
            t15 = teilnahmen[15];
            t16 = teilnahmen[16];
            t17 = teilnahmen[17];
            t18 = teilnahmen[18];
            t19 = teilnahmen[19];
            t20 = teilnahmen[20];
            t21 = teilnahmen[21];
            t22 = teilnahmen[22];
            t23 = teilnahmen[23];
            t24 = teilnahmen[24];
            t25 = teilnahmen[25];
            t26 = teilnahmen[26];
            t27 = teilnahmen[27];

            if (teilnahmen.Count >= 29)
                t28 = teilnahmen[28];
            if (teilnahmen.Count >= 30)
                t29 = teilnahmen[29];
            if (teilnahmen.Count == 31)
                t30 = teilnahmen[30];
        }
    }

    public struct BookingRelationDictionaryValue
    {
        public DateTime Datum, StartDate, EndDate;

        public BookingRelationDictionaryValue(DateTime d, DateTime s, DateTime e)
        {
            Datum = d;
            StartDate = s;
            EndDate = e;
        }
    }

    public class CheckEditTag
    {
        public Teilnehmer Teilnehmer { get; set; }
        public GridColumn Column { get; set; }

        public CheckEditTag(Teilnehmer teilnehmer, GridColumn column)
        {
            Teilnehmer = teilnehmer;
            Column = column;
        }

        public int GetHeaderAsDay()
        {
            if (Column.Header.ToString().Equals(string.Empty))
                return 0;

            var tag = int.Parse(Column.Header.ToString().Split('.')[0], NumberStyles.Integer);
            return tag;
        }
    }
}