using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Forms.VisualStyles;
using System.Windows.Input;
using System.Windows.Media;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;

using BeWo.Controls;
using BeWo.ServiceProxy;
using BeWo.View;
using BeWo.View.Controls;
using BeWo.View.Detail;
using BeWo.View.Detail.Accounting;
using BeWo.View.Detail.Report;
using BeWo.View.Master;
using BeWo.View.Navigation;
using BeWo.View.Report.Auslastung;
using BeWo.View.Report.FLSReport;
using BeWo.View.Search;
using BeWo.ViewModel;

using DevExpress.Xpf.Core;
using DevExpress.Xpf.Core.Native;
using DevExpress.Xpf.Grid;
using DevExpress.XtraReports.UI;
using DevExpress.Xpf.Printing;

namespace BeWo.Core
{
    public static class BeWoUtils
    {
        public static Dictionary<string, string> ParseQuery(string query)
        {
            try
            {
                if (query.IndexOf('?') >= 0)
                {
                    query = query.Split('?')[1];

                    var valueArray = Regex.Split(query, @"[\&]{0,1}[A-Za-z0-9]+[\=]{1}");
                    var paramArray = Regex.Split(query, @"[\=][A-Za-z0-9;]+");

                    valueArray = valueArray.Where(t => !string.IsNullOrWhiteSpace(t)).ToArray();
                    paramArray = paramArray.Where(t => !string.IsNullOrWhiteSpace(t)).ToArray();

                    var queryDictionary = new Dictionary<string, string>();

                    int ixg = 0;
                    foreach (var item in paramArray)
                    {
                        queryDictionary.Add(item.Contains("&") ? Regex.Split(item, @"[\?]|[\&]")[1] : item,
                                            valueArray[ixg]);
                        ixg++;
                        if (ixg >= valueArray.Length)
                            break;
                    }

                    return queryDictionary;
                }
                return new Dictionary<string, string>();
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Error while parsing query '{0}'\n{1}", query, ex.Message), ex);
            }
        }

        private static XtraReport Report { get; set; }
		public static void NavigateToReportUri(string navigateUriString, string title)
		{
			NavigateToReportUri(navigateUriString, title, null);
		}

		public static void NavigateToReportUri(string navigateUriString, string title, DocumentPreview documentPreview)
        {
				BeWoApp.MainControl.StartWaiting();

				StartGetReportStreamAsync(GetReportStreamForWPFControl, navigateUriString,
					ms => BeWoApp.MainControl.Dispatch(delegate
					{
					    var report = new XtraReport();
					    try
					    {
					        var scrollablePageView  = (IScrollInfo)LayoutHelper.FindElement(documentPreview, p => p.GetType() == typeof(DevExpress.Xpf.Printing.Native.ScrollablePageView));
					        if (scrollablePageView != null)
					        {
					            scrollablePageView.PageUp();
					        }

					        report.PrintingSystem.LoadDocument(ms);
					    }
					    catch (Exception)
					    {
					        var msg = System.Text.Encoding.ASCII.GetString(ms.ToArray());
										
					        MessageBox.Show("Beim Öffnen der Druckvorschau ist leider ein Fehler aufgetreten!\n\n" + msg, "Fehler", MessageBoxButton.OK, MessageBoxImage.Exclamation);
					    }

					    ms.Close();
					    ms.Dispose();

						report.DefaultPrinterSettingsUsing.UseLandscape = BeWoApp.AppSettings.PrinterSettingsUseLandscape;
						report.DefaultPrinterSettingsUsing.UseMargins = BeWoApp.AppSettings.PrinterSettingsUseMargins;
						report.DefaultPrinterSettingsUsing.UsePaperKind = BeWoApp.AppSettings.PrinterSettingsUsePaperKind;
									
					    BeWoWindow window = null;

					    var dp = documentPreview;
					    if (dp == null)
					    {
					        dp = new DocumentPreview();
					        window = new BeWoWindow {GroupBoxContent = dp, Owner = BeWoApp.CurrentBeWo.MainWindow};
					        ThemeManager.SetTheme(window, Theme.Office2010Black);
					    }

                        // ReportPreviewModelLandscapeBugWorkaround statt des XtraReportPreviewModels wegen des Landscape-Bugs
                        dp.Model = new ReportPreviewModelLandscapeBugWorkaround(report);
					    ThemeManager.SetTheme(dp, Theme.Office2007Black);
									
					    dp.BarManager.Loaded += delegate
					    {
					        dp.BarManager.Items["documentMap"].IsVisible = false;
					        dp.BarManager.Items["open"].IsVisible = false;
					        dp.BarManager.Items["email"].IsVisible = false;
					        dp.BarManager.Items["watermark"].IsVisible = false;
					        dp.BarManager.Items["pageSetup"].IsVisible = false;
					        dp.BarManager.Items["scaling"].IsVisible = false;
					        dp.BarManager.Items["save"].IsVisible = false;
					        dp.BarManager.Items["printDirect"].IsVisible = false;
					        dp.BarManager.Items["exportText"].IsVisible = false;
					        dp.BarManager.Items["exportCSV"].IsVisible = false;
					        dp.BarManager.Items["exportMHT"].IsVisible = false;
					        dp.BarManager.Items["exportXPS"].IsVisible = false;
					        var item = dp.BarManager.Items["exportRTF"];
					    };
					    if (window != null)
					    {
					        window.rootGroupBox.Header = String.IsNullOrEmpty(title) ? "Druckvorschau" : title;
					        window.Title = "Druckvorschau";
					        window.Show();
					    }
									
					    dp.Visibility = Visibility.Visible;
									
					    BeWoApp.MainControl.EndWaiting();
					}));
        }

		public static void StartGetReportStreamAsync(Func<String, MemoryStream> func, String param, Action<MemoryStream> callback)
		{
			func.BeginInvoke(param,
				cb =>
					{
						try
						{
							var result = func.EndInvoke(cb);
							if (callback != null)
							{
								callback(result);
							}
						}
						catch (Exception e)
						{
							BeWoApp.ShowError(null, e, true);
							BeWoApp.MainControl.EndWaiting();
						}
					},
				null);
		}

	    public static MemoryStream GetReportStreamForWPFControl(string navigateUriString)
        {
			var webClient = new BeWoWebClient();
		    
            var refreshedUriString = RefreshNavigateUriString(navigateUriString);
            var data = webClient.DownloadData(refreshedUriString);

            return new MemoryStream(data);
        }

        public static string RemoveAuthenticationInfoFromUri(string navigateUri)
        {
            var regex = new Regex(@"[\&|\?]?token\=[A-Za-z0-9]+|[\&|\?]?tenant\=[A-Za-z0-9]+|[\&|\?]?username\=[A-Za-z0-9.]+");
            var splittedUri = regex.Split(navigateUri.Split('?')[1]);
            var cleanedSplittedUri = splittedUri.Where(t => !string.IsNullOrWhiteSpace(t)).ToArray();
            var uriValues = cleanedSplittedUri.Aggregate(string.Empty, (current, item) => current + item);

            return navigateUri.Split('?')[0] + "?" + uriValues;
        }

        private static string RefreshNavigateUriString(string navigateUri)
        {
            if (navigateUri.Contains("tenant"))
                navigateUri = RemoveAuthenticationInfoFromUri(navigateUri);

            var tempToken = string.Empty;

            ServiceFacade.DoDownloadServiceSync(s => tempToken = s.CreateTemporaryToken(navigateUri, false));

            var addChar = (navigateUri.Contains("?")) ? "&" : "?";

            var finalUri = string.Format("{0}{1}token={2}", navigateUri, addChar, tempToken);

            return finalUri;
        }

        public static bool CheckPopupEditClickableSpace(PopUpEdit popupedit, MouseButtonEventArgs e)
        {
            var buttonWidth = 22d;
            var pos = e.GetPosition(popupedit);

            if (popupedit.NewButtonVisibility == Visibility.Visible)
                buttonWidth += 22;

            if (popupedit.DeleteButtonVisibility == Visibility.Visible)
                buttonWidth += 22;

            return !(pos.X > popupedit.ActualWidth - buttonWidth);
        }

        public static void UpdateSearchViewObjectList<T, U>(T searchView, U updatedDC)
            where T : GenericSearchView<U>
            where U : class, IDataContract, IFilterableDC
        {
            var newSearchObjectList = new List<U>();

            if (typeof (U) == typeof (CompactSupportConceptDC))
            {
                var uSC = updatedDC as CompactSupportConceptDC;

                newSearchObjectList = searchView.ObjectList;

                if (newSearchObjectList.Contains(updatedDC))
                {
                    newSearchObjectList[newSearchObjectList.IndexOf(updatedDC)] = updatedDC;
                }

                foreach (var oldDC in newSearchObjectList.Select(item => item as CompactSupportConceptDC).Where(oldDC => oldDC.Customer.Equals(uSC.Customer)))
                {
                    oldDC.Customer = uSC.Customer;
                }
            }
            else
            {
                foreach (var oldDC in searchView.ObjectList.Where(oldDC => !newSearchObjectList.Contains(oldDC)))
                {
                    newSearchObjectList.Add(updatedDC.Equals(oldDC) ? updatedDC : oldDC);
                }
            }

            searchView.ObjectList = null;
            searchView.ObjectList = newSearchObjectList;
        }

        public static void OpenModalViewWindow<T, U, V>(
            T viewModel, 
            V ownerView, 
            Action applyChanges, 
            EventHandler<EventArgs<OrganisationVM>> organisationSavedOrUpdated = null, 
            EventHandler<EventArgs<PersonVM>> personSavedOrUpdated = null)
            where T : AbstractDCMapperVM<U>
            where U : IDataContract, new()
            where V : BeWoView
        {
            var tType = typeof(T);
            var View = new BeWoView();

            if (tType == typeof(EmployeeVM))
            {
                View = new EmployeeView(viewModel as EmployeeVM) { ParentView = ownerView, MinWidth = 800, IsInWindow = true };
            }
            else if (tType == typeof(WohnheimVM))
            {
                View = new WohnheimView(viewModel as WohnheimVM) { ParentView = ownerView, MinWidth = 800, IsInWindow = true };
            }
            else if (tType == typeof (OrganisationVM))
            {
                View = new OrganisationView(viewModel as OrganisationVM) { ParentView = ownerView, MinWidth = 800, IsInWindow = true };
                (View as OrganisationView).OrganisationSavedOrUpdated += organisationSavedOrUpdated;
            }
            else if (tType == typeof (PersonVM))
            {
                View = new PersonView(viewModel as PersonVM) {ParentView = ownerView, MinWidth = 800, IsInWindow = true};
                (View as PersonView).PersonSavedOrUpdated += personSavedOrUpdated;
            }
            else if (tType == typeof (TeamVM))
            {
                View = new TeamView(viewModel as TeamVM) {ParentView = ownerView, MinWidth = 800, IsInWindow = true};
            }
            else if(tType==typeof(CustomerVM))
            {
                View = new CustomerView(viewModel as CustomerVM) { ParentView = ownerView, MinWidth = 800, IsInWindow = true };
            }
            else if(tType==typeof(SupportConceptVM))
            {
                View = new SupportConceptView(viewModel as SupportConceptVM) { ParentView = ownerView, MinWidth = 800, IsInWindow = true };
            }
            else
            {
                return;
            }

            View.ModalEditViewUpdateCallback = applyChanges;

            var modalViewWindow = new ModalViewWindow(View, ownerView);

            BeWoApp.MainControl.OpenedModalViewWindows.Add(modalViewWindow);

            foreach (var window in BeWoApp.MainControl.OpenedModalViewWindows.Where(window => !BeWoApp.MainControl.OpenedModalViewWindows.Last().Equals(window)))
            {
                ShowModalBackground(window.RootGrid);
            }

            var dialogResult = modalViewWindow.ShowDialog();

            if (BeWoApp.MainControl.OpenedModalViewWindows.Count > 1)
            {
                var nextToLastWindow = BeWoApp.MainControl.OpenedModalViewWindows.ElementAt(BeWoApp.MainControl.OpenedModalViewWindows.Count - 2);
                nextToLastWindow.RootGrid.Children.RemoveAt(1);
            }

            BeWoApp.MainControl.OpenedModalViewWindows.Remove(modalViewWindow);
        }

        public static bool CheckViewIsCalledFromWindow(BeWoView view)
        {
            return ((Grid) view.Parent).Parent.GetType() == typeof (Window);
        }

        private static void ShowModalBackground(Grid gridToBlock)
        {
            var detailViewBackGround = new Grid
            {
                IsHitTestVisible = true,
                Background = Brushes.White,
                Opacity = .5,
                Name = "DetailViewBackGround"
            };

            if (gridToBlock.Children.OfType<Grid>().Any(obj => obj.Name.Equals("DetailViewBackGround")))
                return;

            Grid.SetColumnSpan(detailViewBackGround, 3);
            Grid.SetRowSpan(detailViewBackGround, 3);
            gridToBlock.Children.Add(detailViewBackGround);
            Panel.SetZIndex(detailViewBackGround, int.MaxValue - 1);
        }

        public static void UpdateAllViews<T>(T updatedObject) where T : IFilterableDC
        {
            var activeView = BeWoApp.MainControl.ActiveView;
            UpdateView(activeView, updatedObject);

            if (BeWoApp.MainControl.OpenedModalViewWindows.Count <= 0)
            {
                return;
            }

            foreach(var view in BeWoApp.MainControl.OpenedModalViewWindows)
            {
                UpdateView(view.DetailView, updatedObject);
            }
        }

        private static void UpdateView<T>(BeWoView view, T updatedObject) where T : IFilterableDC
        {
            if (view.GetType() == typeof (EmployeeView))
            {
                #region EmployeeView
                if (typeof (T) == typeof (CompactCustomerDC))
                {
                    var updatedCustomer = new CompactCustomerDC();

                    ServiceFacade.DoCustomerServiceSync(s => updatedCustomer = s.GetCompactCustomerDC((updatedObject as CompactCustomerDC).CustomerOid));

                    foreach (var item in (view as EmployeeView).ViewModel.CustomerRelations.VMList.Where(item => item.Customer.Equals(updatedCustomer)))
                    {
                        item.Customer = updatedCustomer;
                    }

                    var grid = (view as EmployeeView).rootGrid.FindResource("grid_CustomerRelation") as GridControl;

                    foreach (var item in ((BindingList<CustomerEmployeeRelationVM>) grid.ItemsSource).Where(item => item.Customer.Equals(updatedCustomer)))
                    {
                        item.Customer = null;
                        item.Customer = updatedCustomer;
                    }

                    grid.RefreshData();
                }
                if (typeof (T) == typeof (CompactEmployeeDC))
                {
                    UpdateLoggedInEmployee((updatedObject as CompactEmployeeDC).EmployeeOid);
                    (view as EmployeeView).ReloadViewModel();
                }

                #endregion
            } 
            else if (view.GetType() == typeof(WohnheimView))
            {
                #region WohnheimView 
                if (typeof(T) == typeof(CompactCustomerDC))
                {
                    var updatedCustomer = new CompactCustomerDC();

                    ServiceFacade.DoCustomerServiceSync(s => updatedCustomer = s.GetCompactCustomerDC((updatedObject as CompactCustomerDC).CustomerOid));

                    var grid = (view as WohnheimView).grid_CustomerRelation;

                    foreach (var item in ((BindingList<WohnheimCustomerRelationVM>)grid.ItemsSource).Where(item => item.Customer.Equals(updatedCustomer)))
                    {
                        item.Customer = null;
                        item.Customer = updatedCustomer;
                    }

                    grid.RefreshData();
                }

                if (typeof(T) == typeof(CompactEmployeeDC))
                {
                    var updatedEmployee = new CompactEmployeeDC();

                    ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));

                    var employeeRelationsGrid = (view as WohnheimView).grid_EmployeeRelation;

                    foreach (var item in ((BindingList<WohnheimEmployeeRelationVM>)employeeRelationsGrid.ItemsSource).Where(item => item.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid)))
                    {
                        item.Employee = null;
                        item.Employee = updatedEmployee;
                    }

                    UpdateLoggedInEmployee((updatedObject as CompactEmployeeDC).EmployeeOid);
                }

                #endregion
            }
            else if (view.GetType() == typeof(CustomerView))
            {
                #region CustomerView
                var customerView = view as CustomerView;

                if (typeof(T) == typeof(CompactEmployeeDC))
                {
                    var updatedEmployee = new CompactEmployeeDC();
                    var grid = new GridControl();

                    if (!string.IsNullOrWhiteSpace(customerView.popupedit_employeeRelations.Text))
                    {
                        ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));
                        customerView.ViewModel.EmployeeRelations.NewVM.Employee = null;
                        customerView.ViewModel.EmployeeRelations.NewVM.Employee = updatedEmployee;
                    }
                    else
                    {
                        ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));
                    }

                    grid = (GridControl)customerView.root.Resources["datagrid_EmployeeRelation"];

                    foreach (var item in ((BindingList<CustomerEmployeeRelationVM>)grid.ItemsSource).Where(item => item.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid)))
                    {
                        item.Employee = null;
                        item.Employee = updatedEmployee;
                    }

                    grid.RefreshData();

                    UpdateSearchViewObjectList(customerView.employeesearchview, updatedEmployee);
                    UpdateLoggedInEmployee(updatedEmployee.EmployeeOid);
                }
                else if (typeof(T) == typeof(CompactPersonDC))
                {
                    var grid = new GridControl();
                    var updatedPerson = new CompactPersonDC();

                    ServiceFacade.DoCustomerServiceSync(s => updatedPerson = s.LoadPersonCompact((updatedObject as CompactPersonDC).PersonOid));

                    if (!(string.IsNullOrWhiteSpace(customerView.popupedit_environmentPersonSearch.Text)) && (view as CustomerView).popupedit_environmentPersonSearch.Text.Equals((updatedObject as CompactPersonDC).ToString()))
                    {
                        customerView.ViewModel.EnvironmentPersons.NewVM.Person = null;
                        customerView.ViewModel.EnvironmentPersons.NewVM.Person = updatedPerson;
                    }

                    grid = (GridControl) customerView.root.Resources["grid_PersonRelations"];

                    var vmList        = customerView.ViewModel.EnvironmentPersons.VMList;
                    var relVMs        = vmList.Where(w => w.Person.PersonOid.Equals(updatedPerson.PersonOid)).Where(w => !w.IsNew);
                    var relPersonOids = relVMs.Select(s => s.CommitToDataContract().Customer2PersonOid.Value).ToList();

                    var dataContracts = new List<CustomerPersonRelationDC>();
                    ServiceFacade.DoCustomerServiceSync(s => dataContracts = s.LoadCustomerPersonRelationsByOid(relPersonOids));

                    var test = new List<CustomerPersonRelationVM>();

                    dataContracts.DoForEach(dfe => test.Add(new CustomerPersonRelationVM(dfe)));

                    var vmMap = vmList.Where(w => relVMs.Contains(w)).ToDictionary(vmList.IndexOf, v => v.DataContract.Customer2PersonOid.Value);
                    foreach (var item in vmMap)
                    {
                        vmList[item.Key] = test.First(f => f.DataContract.Customer2PersonOid.Value.Equals(item.Value));
                    }

                    grid.RefreshData();

                    UpdateSearchViewObjectList(customerView.personsearchview, updatedPerson);
                }
                else if (typeof(T) == typeof(CompactOrganisationDC))
                {
                    var organisationToUpdate = updatedObject as CompactOrganisationDC;
                    var updatedOrganisation = new CompactOrganisationDC();
                    var organisationRelationGrid = new GridControl();
                    var costBearerRelationGrid = new GridControl();

                    if ((updatedObject as CompactOrganisationDC) == null)
                    {
                        return;
                    }

                    organisationRelationGrid = (GridControl) customerView.root.Resources["grid_OrganisationRelations"];
                    costBearerRelationGrid = (GridControl) customerView.root.Resources["grid_costBearer"];

                    ServiceFacade.DoCustomerServiceSync(s => updatedOrganisation = s.LoadOrganisationCompact(organisationToUpdate.OrganisationOid));

                    if (!(string.IsNullOrWhiteSpace(customerView.popupedit_costBearer.Text)) && customerView.popupedit_costBearer.Text.Equals(organisationToUpdate.ToString()))
                    {
                        customerView.ViewModel.CostBearers.NewVM.CostBearer = null;
                        customerView.ViewModel.CostBearers.NewVM.CostBearer = updatedOrganisation;
                        customerView.popupedit_costBearer.Text = updatedOrganisation.ToString();
                    }

                    foreach (var item in (customerView.ViewModel.CostBearers.VMList).Where(item => item.CostBearer.Equals(updatedOrganisation)))
                    {
                        item.CostBearer = null;
                        item.CostBearer = updatedOrganisation;
                    }

                    if (!(string.IsNullOrWhiteSpace(customerView.popupedit_environmentOrganisationSearch.Text)) && customerView.popupedit_environmentOrganisationSearch.Text.Equals(organisationToUpdate.ToString()))
                    {
                        customerView.ViewModel.EnvironmentOrganisations.NewVM.Organisation = null;
                        customerView.ViewModel.EnvironmentOrganisations.NewVM.Organisation = updatedOrganisation;
                        customerView.popupedit_environmentOrganisationSearch.Text = updatedOrganisation.ToString();
                    }

                    var vmList              = customerView.ViewModel.EnvironmentOrganisations.VMList;
                    var relVMs              = vmList.Where(w => w.Organisation.OrganisationOid.Equals(updatedOrganisation.OrganisationOid)).Where(w => !w.IsNew);
                    var relOrganisationOids = relVMs.Select(s => s.CommitToDataContract().Customer2OrganisationOid.Value).ToList();
                    var dataContracts       = new List<CustomerOrganisationRelationDC>();
                    var test                = new List<CustomerOrganisationRelationVM>();

                    ServiceFacade.DoCustomerServiceSync(s => dataContracts = s.LoadCustomerOrganisationRelationsByOid(relOrganisationOids));

                    dataContracts.DoForEach(dfe => test.Add(new CustomerOrganisationRelationVM(dfe)));

                    var vmMap = vmList.Where(w => relVMs.Contains(w)).ToDictionary(vmList.IndexOf, v => v.DataContract.Customer2OrganisationOid.Value);

                    foreach (var item in vmMap)
                    {
                        vmList[item.Key] = test.First(f => f.DataContract.Customer2OrganisationOid.Value.Equals(item.Value));
                    }

                    organisationRelationGrid.RefreshData();
                    costBearerRelationGrid.RefreshData();

                    UpdateSearchViewObjectList(customerView.costbearersearchview, updatedOrganisation);
                    UpdateSearchViewObjectList(customerView.organisationsearchview, updatedOrganisation);
                }
                else if (typeof(T) == typeof(CompactTeamDC))
                {
                    var teamToUpdate = updatedObject as CompactTeamDC;
                    var updatedTeam = new CompactTeamDC();
                    var grid = (GridControl) customerView.root.Resources["datagrid_TeamRelation"];

                    ServiceFacade.DoEmployeeServiceSync(s => updatedTeam = s.LoadCompactTeam(teamToUpdate.TeamOid));

                    if (!(string.IsNullOrWhiteSpace(customerView.popupedit_teamRelations.Text)) && customerView.popupedit_teamRelations.Text.Equals(teamToUpdate.ToString()))
                    {
                        ServiceFacade.DoEmployeeServiceSync(s => updatedTeam = s.LoadCompactTeam(teamToUpdate.TeamOid));
                        customerView.ViewModel.TeamRelations.NewVM.Team = null;
                        customerView.ViewModel.TeamRelations.NewVM.Team = updatedTeam;
                    }

                    foreach (var item in ((BindingList<CustomerTeamRelationVM>) grid.ItemsSource).Where(item => item.Team.Equals(updatedTeam)))
                    {
                        item.Team = null;
                        item.Team = updatedTeam;
                    }

                    grid.RefreshData();
                    UpdateSearchViewObjectList(customerView.teamsearchview, updatedTeam);
                }
                else if (typeof (T) == typeof (CompactCustomerDC))
                {
                    customerView.ReloadViewModel();
                }
                #endregion
            }
            else if (view.GetType() == typeof(OrganisationView))
            {
                #region OrganisationView
                if (typeof (T) == typeof (CompactPersonDC))
                {
                    var organisationView = view as OrganisationView;
                    var updatedPerson    = new CompactPersonDC();
                    var grid             = (GridControl) organisationView.gridroot.Resources["datagrid_PersonRelation"];

                    ServiceFacade.DoCustomerServiceSync(s => updatedPerson = s.LoadPersonCompact((updatedObject as CompactPersonDC).PersonOid));

                    var vmList        = organisationView.ViewModel.PersonRelations.VMList;
                    var relVMs        = vmList.Where(w => w.Person.PersonOid.Equals(updatedPerson.PersonOid)).Where(w => !w.IsNew);
                    var relPersonOids = relVMs.Select(s => s.CommitToDataContract().Organisation2PersonOid.Value).ToList();
                    var dataContracts = new List<OrganisationPersonRelationDC>();
                    var test          = new List<OrganisationPersonRelationVM>();

                    ServiceFacade.DoOperationsServiceSync(s => dataContracts = s.LoadOrganisationPersonRelationsByOid(relPersonOids));

                    dataContracts.DoForEach(dfe => test.Add(new OrganisationPersonRelationVM(dfe)));

                    var vmMap = vmList.Where(w => relVMs.Contains(w)).ToDictionary(vmList.IndexOf, v => v.DataContract.Organisation2PersonOid.Value);
                    foreach (var item in vmMap)
                    {
                        vmList[item.Key] = test.First(f => f.DataContract.Organisation2PersonOid.Value.Equals(item.Value));
                    }

                    grid.RefreshData();
                }
                else if (typeof (T) == typeof (CompactOrganisationDC))
                {
                    (view as OrganisationView).ReloadViewModel();
                }
                #endregion
            }
            else if (view.GetType() == typeof(BookingView))
            {
                #region BookingView

                if (typeof (T) != typeof (CompactEmployeeDC))
                    return;

                var bookingView = view as BookingView;
                var updatedEmployee = new CompactEmployeeDC();

                ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));

                var sourceNew = bookingView.combobox_newEmployee.ItemsSource as ObservableCollection<CompactEmployeeDC>;
                var sourceEdit = bookingView.combobox_editEmployee.ItemsSource as ObservableCollection<CompactEmployeeDC>;

                var selectedNewIndex = bookingView.combobox_newEmployee.SelectedIndex;
                var selectedEditIndex = bookingView.combobox_editEmployee.SelectedIndex;

                foreach (var item in bookingView.ViewModel.VMList.Where(item => item.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid)))
                {
                    item.Employee = new CompactEmployeeDC();
                    item.Employee = updatedEmployee;
                }

                for (var i = 0; i < sourceNew.Count; i++)
                {
                    if (!sourceNew[i].EmployeeOid.Equals(updatedEmployee.EmployeeOid)) continue;
                    sourceNew[i] = new CompactEmployeeDC();
                    sourceNew[i] = updatedEmployee;
                }

                for (var i = 0; i < sourceNew.Count; i++)
                {
                    if (!sourceEdit[i].EmployeeOid.Equals(updatedEmployee.EmployeeOid)) continue;
                    sourceEdit[i] = new CompactEmployeeDC();
                    sourceEdit[i] = updatedEmployee;
                }

                bookingView.combobox_newEmployee.ItemsSource = sourceNew;
                bookingView.combobox_editEmployee.ItemsSource = sourceEdit;

                bookingView.combobox_newEmployee.SelectedIndex = selectedNewIndex;
                bookingView.combobox_editEmployee.SelectedIndex = selectedEditIndex;

                UpdateLoggedInEmployee(updatedEmployee.EmployeeOid);
                #endregion
            }
            else if (view.GetType() == typeof(FinanceView))
            {
                #region FinanceView
                var v = (view as FinanceView);
                var settle = v.tabitem_settlementinvoice.Content as SettlementInvoiceView;
                var eq = v.tabitem_equityinvoice.Content as EquityInvoiceView;
                var gi = v.tabitem_otherinvoice.Content as GeneralInvoiceView;
                var serv = v.tabitem_collectiveinvoice.Content as ServiceInvoiceView;
                var atb = v.tabitem_financeBooking.Content as AccountingTransactionBookingView;
                
                if (typeof (T) == typeof (CompactCustomerDC))
                {
                    var updatedCustomer = new CompactCustomerDC();
                    ServiceFacade.DoCustomerServiceSync(s => updatedCustomer = s.GetCompactCustomerDC((updatedObject as CompactCustomerDC).CustomerOid));

                    if (atb != null)
                    {
                        foreach (var item in atb.ViewModel.AccountingTransactionVMList.Where(item => item.SupportConcept.Customer.Equals(updatedCustomer)))
                        {
                            item.SupportConcept.Customer = new CompactCustomerDC();
                            item.SupportConcept.Customer = updatedCustomer;
                        }

                        foreach (var item in atb.FlatSupportConceptItems.Where(item => item.SupportConceptTreeNodeDC != null).Where(item => item.SupportConceptTreeNodeDC.Customer.Equals(updatedCustomer)))
                        {
                            item.SupportConceptTreeNodeDC.Customer = new CompactCustomerDC();
                            item.SupportConceptTreeNodeDC.Customer = updatedCustomer;
                        }

                        UpdateSingleSupportConceptSelectionControl(atb.supportConceptSelectionControl, updatedCustomer);
                    }
                    if (settle != null)
                    {
                        if (settle.SelectedSupportConcept != null)
                        {
                            if (settle.SelectedSupportConcept.Customer.Equals((updatedObject as CompactCustomerDC)))
                            {
                                settle.SelectedSupportConcept.Customer = new CompactCustomerDC();
                                settle.SelectedSupportConcept.Customer = updatedCustomer;

                                settle.popupedit_CostBeaerer.Text = string.Format("{0}, {1} {2}", settle.SelectedSupportConcept.Customer.LastName,
                                                                                                  settle.SelectedSupportConcept.Customer.FirstName,
                                                                                                  settle.SelectedSupportConcept.Customer.DateOfBirthString);
                            }

                            UpdateSearchViewObjectList(settle.supportconceptsearchview, settle.SelectedSupportConcept);
                        }
                        else
                        {
                            UpdateSearchViewObjectList(settle.supportconceptsearchview, new CompactSupportConceptDC{Customer = updatedCustomer});
                        }
                    }
                    if (eq != null)
                    {
                        if (eq.SelectedSupportConcept != null)
                        {
                            eq.SelectedSupportConcept.Customer = new CompactCustomerDC();
                            eq.SelectedSupportConcept.Customer = updatedCustomer;

                            eq.popupedit_CostBeaerer.Text = string.Format("{0}, {1} {2}", eq.SelectedSupportConcept.Customer.LastName,
                                                                                          eq.SelectedSupportConcept.Customer.FirstName,
                                                                                          eq.SelectedSupportConcept.Customer.DateOfBirthString);

                            UpdateSearchViewObjectList(eq.supportconceptsearchview, eq.SelectedSupportConcept);
                        }
                        else
                        {
                            UpdateSearchViewObjectList(eq.supportconceptsearchview, new CompactSupportConceptDC { Customer = updatedCustomer });
                        }
                    }
                    if (serv != null)
                    {
                        if (serv.ViewModel.SelectedSupportConcept != null)
                        {
                            if (serv.ViewModel.SelectedSupportConcept.Customer.Equals((updatedObject as CompactCustomerDC)))
                            {
                                serv.ViewModel.SelectedSupportConcept.Customer = new CompactCustomerDC();
                                serv.ViewModel.SelectedSupportConcept.Customer = updatedCustomer;

                                serv.popupedit_supportConcept.Text = string.Format("{0}, {1} {2}", serv.ViewModel.SelectedSupportConcept.Customer.LastName,
                                                                                                   serv.ViewModel.SelectedSupportConcept.Customer.FirstName,
                                                                                                   serv.ViewModel.SelectedSupportConcept.Customer.DateOfBirthString);

                                UpdateSearchViewObjectList(serv.supportConcept_search, serv.ViewModel.SelectedSupportConcept);
                            }
                        }
                        else
                        {
                            UpdateSearchViewObjectList(serv.supportConcept_search, new CompactSupportConceptDC { Customer = updatedCustomer });
                        }
                    }
                }
                else if (typeof(T) == typeof(CompactSupportConceptDC))
                {
                    var updatedSupportConcept = new CompactSupportConceptDC();
                    ServiceFacade.DoCustomerServiceSync(s => updatedSupportConcept = s.LoadCompactSupportConceptDC((updatedObject as CompactSupportConceptDC).SupportConceptOid, BeWoApp.LoggedOnEmployee.EmployeeOid));

                    if (eq != null && eq.SelectedSupportConcept != null)
                    {
                        eq.ReloadViewModel();
                        eq.popupedit_CostBeaerer.Text = string.Format("{0}, {1} {2}", updatedSupportConcept.Customer.LastName, 
                                                                                      updatedSupportConcept.Customer.FirstName, 
                                                                                      updatedSupportConcept.Customer.DateOfBirthString);

                        UpdateSearchViewObjectList(eq.supportconceptsearchview, eq.SelectedSupportConcept);
                    }
                    if (settle != null && settle.SelectedSupportConcept != null)
                    {
                        settle.ReloadViewModel();
                        settle.popupedit_CostBeaerer.Text = string.Format("{0}, {1} {2}", updatedSupportConcept.Customer.LastName,
                                                                                          updatedSupportConcept.Customer.FirstName,
                                                                                          updatedSupportConcept.Customer.DateOfBirthString);

                        UpdateSearchViewObjectList(settle.supportconceptsearchview, settle.SelectedSupportConcept);
                    }
                    if (serv != null && serv.ViewModel.SelectedSupportConcept != null)
                    {
                        if (serv.ViewModel.SelectedSupportConcept.Equals(updatedSupportConcept))
                            serv.ViewModel.SelectedSupportConcept = updatedSupportConcept;

                        UpdateSearchViewObjectList(serv.supportConcept_search, updatedSupportConcept);
                    }
                }
                else if (typeof(T) == typeof(CompactOrganisationDC))
                {
                    var updatedOrganisation = new CompactOrganisationDC();
                    ServiceFacade.DoCustomerServiceSync(s => updatedOrganisation = s.LoadOrganisationCompact((updatedObject as CompactOrganisationDC).OrganisationOid));

                    if (gi != null)
                    {
                        if (gi.SelectedOrganisation != null)
                        {
                            if (gi.SelectedOrganisation.Equals(updatedOrganisation))
                            {
                                gi.SelectedOrganisation = null;
                                gi.SelectedOrganisation = updatedOrganisation;
                            }

                            gi.popupedit_Recipient.Text = updatedOrganisation.ToString();
                        }

                        UpdateSearchViewObjectList(gi.recipientsearchview, updatedOrganisation);
                    }
                    if (serv != null)
                    {
                        if (serv.ViewModel.SelectedCostBearer != null)
                            if (serv.ViewModel.SelectedCostBearer.Equals(updatedOrganisation))
                                serv.ViewModel.SelectedCostBearer = updatedOrganisation;

                        UpdateSearchViewObjectList(serv.organisationSearchView, updatedOrganisation);
                    }
                }
                #endregion
            }
            else if (view.GetType() == typeof(SupportConceptView))
            {
                #region SupportConceptView
                var SupportConceptView = view as SupportConceptView;

                if (typeof (T) == typeof (CompactEmployeeDC))
                {
                    var updatedEmployee = new CompactEmployeeDC();

                    ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));

                    for (var i = 0; i < SupportConceptView.ViewModel.Tasks.NewVM.Employees.Count; i++)
                    {
                        if (!SupportConceptView.ViewModel.Tasks.NewVM.Employees[i].EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                        {
                            continue;
                        }

                        SupportConceptView.ViewModel.Tasks.NewVM.Employees[i] = null;
                        SupportConceptView.ViewModel.Tasks.NewVM.Employees[i] = updatedEmployee;
                    }

                    for (var i = 0; i < SupportConceptView.ViewModel.CostBearerRelations.VMList.Count; i++)
                    {
                        var currentSC = SupportConceptView.ViewModel.CostBearerRelations.VMList[i];

                        for (var j = 0; j < currentSC.ApprovalPeriodList.VMList.Count; j++)
                        {
                            var currentAP = currentSC.ApprovalPeriodList.VMList[j];

                            if (currentAP.SupportConceptApprovalEmployeeRelations.VMList.Any(a => a.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid)))
                            {
                                // Nur einmal in der Liste
                                var employeeContainingRel = currentAP.SupportConceptApprovalEmployeeRelations.VMList.FirstOrDefault(f => f.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid));
                                if (employeeContainingRel != null)
                                {
                                    employeeContainingRel.Employee = null;
                                    employeeContainingRel.Employee = updatedEmployee;
                                }
                            }
                        }
                    }

                    if (SupportConceptView.ViewModel.CostBearerRelations.VMList.Any(a => a.ApprovalPeriodList.VMList.Any(a2 => a2.SupportConceptApprovalEmployeeRelations.VMList.Any(a3 => a3.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid)))))
                    {
                        var emp = SupportConceptView.SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.VMList.FirstOrDefault(f => f.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid));
                        if (emp != null)
                        {
                            emp.Employee       = null;
                            emp.Employee       = updatedEmployee;
                            emp.EmployeeString = updatedEmployee.ToString();
                        }
                    }

                    if (SupportConceptView.SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                    {
                        SupportConceptView.SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Employee       = null;
                        SupportConceptView.SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.Employee       = updatedEmployee;
                        SupportConceptView.SelectedApprovalPeriodVM.SupportConceptApprovalEmployeeRelations.NewVM.EmployeeString = updatedEmployee.ToString();
                    }

                    if (SupportConceptView.ViewModel.Originator.EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                    {
                        SupportConceptView.ViewModel.Originator    = null;
                        SupportConceptView.ViewModel.Originator    = updatedEmployee;
                        SupportConceptView.popupedit_employee.Text = updatedEmployee.ToString();
                    }

                    if (BeWoApp.LoggedOnUser.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                    {
                        BeWoApp.LoggedOnUser.Employee = updatedEmployee;
                    }

                    SupportConceptView.popupedit_employee.Text = updatedEmployee.ToString();
                    UpdateLoggedInEmployee(updatedEmployee.EmployeeOid);
                    UpdateSearchViewObjectList(SupportConceptView.employeesearchview, updatedEmployee);

                    foreach (var item in SupportConceptView.ViewModel.Tasks.VMList)
                    {
                        for (var i = 0; i < item.Employees.Count; i++)
                        {
                            var prevDirty = item.IsDirty;
                            if (!item.Employees[i].EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                            {
                                continue;
                            }

                            item.Employees[i] = updatedEmployee;

                            if (!prevDirty && item.IsDirty)
                            {
                                item.SetDirty(false);
                            }
                        }
                    }

                    SupportConceptView.grid_tasks.RefreshData();
                }
                else if (typeof(T) == typeof(CompactPersonDC))
                {
                    var updatedPerson = new CompactPersonDC();

                    ServiceFacade.DoCustomerServiceSync(s => updatedPerson = s.LoadPersonCompact((updatedObject as CompactPersonDC).PersonOid));

                    ((SupportConceptCostBearerRelVM)SupportConceptView.tabcontrol_costbearers.SelectedItem)
                        .CostBearerContactPerson = null;
                    ((SupportConceptCostBearerRelVM)SupportConceptView.tabcontrol_costbearers.SelectedItem)
                        .CostBearerContactPerson = updatedPerson;
                }
                else if (typeof (T) == typeof (CompactCustomerDC))
                {
                    var updatedCustomer = SupportConceptView.ViewModel.Customer;

                    ServiceFacade.DoCustomerServiceSync(s => updatedCustomer = s.GetCompactCustomerDC(SupportConceptView.ViewModel.Customer.CustomerOid));

                    SupportConceptView.ViewModel.Customer = new CompactCustomerDC();
                    SupportConceptView.ViewModel.Customer = updatedCustomer;

                    SupportConceptView.popupedit_customer.Text = updatedCustomer.ToString();

                    UpdateSearchViewObjectList(SupportConceptView.customersearchview, updatedCustomer);
                }
                #endregion
            }
            else if (view.GetType() == typeof(ServiceRecordView2))
            {
                #region ServiceRecordView2
                var ServiceRecordView2 = view as ServiceRecordView2;

                if (typeof (T) == typeof (CompactCustomerDC))
                {
                    var updatedCustomer = new CompactCustomerDC();

                    ServiceFacade.DoCustomerServiceSync(s => updatedCustomer = s.GetCompactCustomerDC((updatedObject as CompactCustomerDC).CustomerOid));

                    foreach (var item in ServiceRecordView2.ViewModel.VMList.Where(item => item.Customer.Equals(updatedCustomer)))
                    {
                        item.Customer = new CompactCustomerDC();
                        item.Customer = updatedCustomer;
                    }

                    ServiceRecordView2.multiSupportConceptControl.UpdateSupportConcepts(updatedCustomer);
                    ServiceRecordView2.multiSupportConceptControl.UpdateListBox();

                    UpdateSingleSupportConceptSelectionControl(ServiceRecordView2.supportConceptSelectionControl, updatedCustomer);
                }
                else if (typeof (T) == typeof (CompactEmployeeDC))
                {
                    var updatedEmployee = new CompactEmployeeDC();
                    ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));

                    UpdateSearchViewObjectList(ServiceRecordView2.employeeSearchView, updatedEmployee);
                    ServiceRecordView2.popupedit_employee.Text = updatedEmployee.ToString();

                    UpdateLoggedInEmployee((updatedObject as CompactEmployeeDC).EmployeeOid);

                    for (var i = 0; i < ServiceRecordView2.multiEmployeeControl.SelectedEmployees.Count; i++)
                    {
                        if (!ServiceRecordView2.multiEmployeeControl.SelectedEmployees[i].EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                        {
                            continue;
                        }

                        ServiceRecordView2.multiEmployeeControl.SelectedEmployees[i] = new CompactEmployeeDC();
                        ServiceRecordView2.multiEmployeeControl.SelectedEmployees[i] = updatedEmployee;
                    }

                    ServiceRecordView2.multiEmployeeControl.UpdateListBox();
                    UpdateSearchViewObjectList(ServiceRecordView2.multiEmployeeControl.employeesearchview, updatedEmployee);

                    if (ServiceRecordView2.ViewModel.BedarfsMedViewModel.NewVM.Employee != null && ServiceRecordView2.ViewModel.BedarfsMedViewModel.NewVM.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                    {
                        ServiceRecordView2.ViewModel.BedarfsMedViewModel.NewVM.Employee = updatedEmployee;
                        ServiceRecordView2.popupedit_employee_bedarfsmed.Text = updatedEmployee.ToString();
                        UpdateSearchViewObjectList(ServiceRecordView2.MedRecordEmployeeSearchView, updatedEmployee);
                    }

                    // TODO: Bedarfsmedikationen
                    UpdateSearchViewObjectList(ServiceRecordView2.MedRecordEmployeeSearchView, updatedEmployee);
                    

                     foreach (var item in ((BindingList<MedRecordVM>)ServiceRecordView2.MedRecordGridControl.ItemsSource).Where(item => item.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid)))
                    {
                        item.Employee = null;
                        item.Employee = updatedEmployee;
                    }

                    ServiceRecordView2.MedRecordGridControl.RefreshData();

                    if (ServiceRecordView2.ViewModel.CustomerNodes.Count <= 0 || ServiceRecordView2.ViewModel.ServiceRecordsForSelectedCustomer == null)
                    {
                        return;
                    }

                    foreach (var item in ServiceRecordView2.ViewModel.ServiceRecordsForSelectedCustomer.Where(item => item.Employee.EmployeeOid.Equals(updatedEmployee.EmployeeOid)))
                    {
                        item.Employee = null;
                        item.Employee = updatedEmployee;
                    }

                    ServiceRecordView2.ViewModel.RefreshServiceRecordsForSelectedTreeNode();
                }
                else if (typeof(T) == typeof(CompactOrganisationDC))
                {
                    var updatedOrganisation = new CompactOrganisationDC();

                    ServiceFacade.DoCustomerServiceSync(s => updatedOrganisation = s.LoadOrganisationCompact((updatedObject as CompactOrganisationDC).OrganisationOid));

                    foreach (var item in ServiceRecordView2.ViewModel.VMList.Where(item => item.CostBearer.Equals(updatedOrganisation)))
                    {
                        item.CostBearer = new CompactOrganisationDC();
                        item.CostBearer = updatedOrganisation;
                    }
                }
                #endregion
            }
            else if (view.GetType() == typeof(TeamView))
            {
                #region TeamView
                if (typeof (T) == typeof (CompactEmployeeDC))
                {
                    var TeamView = view as TeamView;
                    var updatedEmployee = new CompactEmployeeDC();

                    ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));

                    if (TeamView.ViewModel.Leader.Equals(updatedObject as CompactEmployeeDC))
                    {
                        TeamView.ViewModel.Leader = null;
                        TeamView.ViewModel.Leader = updatedEmployee;
                    }

                    if (TeamView.ViewModel.Member.Contains(updatedEmployee))
                    {
                        var newMember = new ObservableSortCollection<CompactEmployeeDC>();
                        foreach (var item in TeamView.ViewModel.Member)
                            newMember.Add(item.EmployeeOid.Equals(updatedEmployee.EmployeeOid) ? updatedEmployee : item);

                        TeamView.ViewModel.Member = null;
                        TeamView.ViewModel.Member = newMember;
                    }

                    if (TeamView.ViewModel.Leader.EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                    {
                        TeamView.ViewModel.Leader = null;
                        TeamView.ViewModel.Leader = updatedEmployee;
                    }

                    UpdateSearchViewObjectList(TeamView.employeesearchview, updatedEmployee);
                    UpdateSearchViewObjectList(TeamView.leaderSearchView, updatedEmployee);
                    UpdateLoggedInEmployee(updatedEmployee.EmployeeOid);
                }
                else if (typeof (T) == typeof (CompactTeamDC))
                {
                    (view as TeamView).ReloadViewModel();
                }
                #endregion
            }
            else if (view.GetType() == typeof(UserView))
            {
                #region UserView
                var updatedEmployee = new CompactEmployeeDC();
                var UserView = view as UserView;

                ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee(UserView.ViewModel.Employee.EmployeeOid));

                UserView.ViewModel.Employee = null;
                UserView.ViewModel.Employee = updatedEmployee;

                var myView = new BeWoView();
                BeWoApp.MainControl.Views.TryGetValue(UIContext.User, out myView);

                var naviView = myView as UserNavigationView;
				if (naviView != null)
				{
					if (naviView.ObjectList.Contains(updatedEmployee))
					{
						var copiedList = naviView.ObjectList as List<IFilterableDC>;
						copiedList[copiedList.IndexOf(updatedEmployee)] = new CompactEmployeeDC();
						copiedList[copiedList.IndexOf(updatedEmployee)] = updatedEmployee;
						naviView.ObjectList = copiedList;
					}

					if (naviView.RecentList.Contains(updatedEmployee))
					{
						var copiedList = naviView.RecentList as List<IFilterableDC>;
						copiedList[copiedList.IndexOf(updatedEmployee)] = new CompactEmployeeDC();
						copiedList[copiedList.IndexOf(updatedEmployee)] = updatedEmployee;
						naviView.RecentList = copiedList;
					}
				}
                UpdateSearchViewObjectList(UserView.employeeSearchView, updatedEmployee);
                UpdateLoggedInEmployee(updatedEmployee.EmployeeOid);
                #endregion
            }
            else if (view.GetType() == typeof(ReportView))
            {
                #region ReportView
                var v = view as ReportView;

                var aus = new BeWoView(); v.OpenViews.TryGetValue(v.tabitem_maReport, out aus);
                var fls = new BeWoView(); v.OpenViews.TryGetValue(v.tabitem_flsReport, out fls);
                var serv = new BeWoView(); v.OpenViews.TryGetValue(v.tabitem_serviceOverview, out serv);
                
                if (typeof (T) == typeof (CompactCustomerDC))
                {
                    var updatedCustomer = new CompactCustomerDC();
                    ServiceFacade.DoCustomerServiceSync(s => updatedCustomer = s.GetCompactCustomerDC((updatedObject as CompactCustomerDC).CustomerOid));

                    var fls2 = fls as FLSReportView;
                    if (fls2 != null)
                    {
                        if (fls2._SelectedCustomer != null)
                        {
                            if (fls2._LastSelectedCustomer != null)
                                if (fls2._LastSelectedCustomer.Equals(updatedCustomer))
                                    fls2._LastSelectedCustomer = updatedCustomer;

                            fls2._SelectedCustomer = updatedCustomer;
                            fls2.popupedit_client.Text = updatedCustomer.ToString();
                        }

                        UpdateSearchViewObjectList(fls2.customerSearchView, updatedCustomer);
                    }

                    var serv2 = serv as ServicesReportView;
                    if (serv != null)
                    {
                        if (serv2.Customer != null)
                        {
                            serv2.Customer = updatedCustomer;
                            serv2.popupedit_customer.Text = updatedCustomer.ToString();
                        }

                        UpdateSearchViewObjectList(serv2.customersearchview, updatedCustomer);
                    }
                }
                if (typeof (T) == typeof (CompactEmployeeDC))
                {
                    var updatedEmployee = new CompactEmployeeDC();
                    ServiceFacade.DoEmployeeServiceSync(s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));

                    var aus2 = aus as AuslastungReportView;
                    if (aus2 != null)
                    {
                        if (aus2._SelectedEmployee != null)
                        {
                            if (aus2._SelectedEmployee != null)
                                if (aus2._SelectedEmployee.EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                                    aus2._SelectedEmployee = updatedEmployee;

                            if (aus2._LastSelectedEmployee != null)
                                if (aus2._LastSelectedEmployee.EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                                    aus2._LastSelectedEmployee = updatedEmployee;

                            if (aus2._SelectedEmployee != null)
                                aus2.popupedit_employee.Text = updatedEmployee.ToString();
                        }

                        UpdateSearchViewObjectList(aus2.employeesearchview, updatedEmployee);
                    }

                    var fls2 = fls as FLSReportView;
                    if (fls2 != null)
                    {
                        if (fls2._SelectedEmployee != null)
                        {
                            if (fls2._LastSelectedEmployee != null)
                                if (fls2._LastSelectedEmployee.EmployeeOid.Equals(updatedEmployee.EmployeeOid))
                                    fls2._LastSelectedEmployee = updatedEmployee;

                            fls2._SelectedEmployee = updatedEmployee;
                            fls2.popupedit_employee.Text = updatedEmployee.ToString();
                        }

                        UpdateSearchViewObjectList(fls2.employeeSearchView, updatedEmployee);
                    }

                    var serv2 = serv as ServicesReportView;
                    if (serv2 != null)
                    {
                        if (serv2.Employee != null)
                        {
                            serv2.Employee = updatedEmployee;
                            serv2.popupedit_employee.Text = updatedEmployee.ToString();
                        }

                        UpdateSearchViewObjectList(serv2.employeesearchview, updatedEmployee);
                    }

                    UpdateLoggedInEmployee(updatedEmployee.EmployeeOid);
                }
                if (typeof (T) == typeof (CompactOrganisationDC))
                {
                    var updatedOrganisation = new CompactOrganisationDC();
                    ServiceFacade.DoCustomerServiceSync(s => updatedOrganisation = s.LoadOrganisationCompact((updatedObject as CompactOrganisationDC).OrganisationOid));

                    var serv2 = serv as ServicesReportView;
                    if (serv2 != null)
                    {
                        if (serv2.Organisation != null)
                        {
                            serv2.Organisation = updatedOrganisation;
                            serv2.popupedit_costbearer.Text = updatedOrganisation.ToString();
                        }

                        UpdateSearchViewObjectList(serv2.organisationsearchview, updatedOrganisation);
                    }
                }
                if (typeof (T) == typeof (CompactTeamDC))
                {
                    var updatedTeam = new CompactTeamDC();
                    ServiceFacade.DoEmployeeServiceSync(s => updatedTeam = s.LoadCompactTeam((updatedObject as CompactTeamDC).TeamOid));

                    var aus2 = aus as AuslastungReportView;
                    if (aus2 != null)
                    {
                        if (aus2._SelectedTeam != null)
                        {
                            if (aus2._SelectedTeam.Equals(updatedTeam))
                                aus2._SelectedTeam = updatedTeam;

                            if (aus2._LastSelectedTeam != null)
                                if (aus2._LastSelectedTeam.Equals(updatedTeam))
                                    aus2._LastSelectedTeam = updatedTeam;

                            aus2.popupedit_team.Text = updatedTeam.ToString();
                        }

                        UpdateSearchViewObjectList(aus2.teamsearchview, updatedTeam);
                    }
                }
                #endregion
            }
            else if (view.GetType() == typeof (PersonView))
            {
                #region PersonView
                if (typeof (T) == typeof (CompactOrganisationDC))
                {
                    var PersonView = view as PersonView;
                    var grid_Relations = (GridControl)PersonView.rootGrid.Resources["grid_Relations"];
                    var updatedOrganisation = new CompactOrganisationDC();

                    ServiceFacade.DoCustomerServiceSync(s => updatedOrganisation = s.LoadOrganisationCompact((updatedObject as CompactOrganisationDC).OrganisationOid));

                    if (!(string.IsNullOrWhiteSpace(PersonView.popupedit_organisation.Text)) && PersonView.popupedit_organisation.Text.Equals((updatedObject as CompactOrganisationDC).Name))
                        PersonView.popupedit_organisation.Text = updatedOrganisation.ToString();

                    foreach (var item in PersonView.ViewModel.OrganisationRelations.VMList.Where(item => item.Organisation.OrganisationOid == updatedOrganisation.OrganisationOid))
                        item.OrganisationString = updatedOrganisation.Name;

                    grid_Relations.RefreshData();

					if (PersonView.ViewModel.OrganisationRelations.NewVM != null && PersonView.ViewModel.OrganisationRelations.NewVM.Organisation != null)
						if (PersonView.ViewModel.OrganisationRelations.NewVM.Organisation.OrganisationOid.Equals(updatedOrganisation.OrganisationOid))
							PersonView.ViewModel.OrganisationRelations.NewVM.OrganisationString = updatedOrganisation.Name;

                    UpdateSearchViewObjectList((view as PersonView).organisationSearchView, updatedOrganisation);
                }
                else if (typeof (T) == typeof (CompactPersonDC))
                {
                    (view as PersonView).ReloadViewModel();
                }
                #endregion
            }
            else if (view.GetType() == typeof (AdditionalServiceView))
            {
                #region AdditionalServiceView

                var additionalServiceView = view as AdditionalServiceView;

                if (typeof (T) == typeof (CompactEmployeeDC))
                {
                    var updatedEmployee = new CompactEmployeeDC();
                    ServiceFacade.DoEmployeeServiceSync(
                        s => updatedEmployee = s.LoadCompactEmployee((updatedObject as CompactEmployeeDC).EmployeeOid));

                    UpdateLoggedInEmployee((updatedObject as CompactEmployeeDC).EmployeeOid);

                    for (var i = 0; i < additionalServiceView.MultiEmployeeControlAddServ.SelectedEmployees.Count; i++)
                    {
                        if (
                            !additionalServiceView.MultiEmployeeControlAddServ.SelectedEmployees[i].EmployeeOid.Equals(
                                updatedEmployee.EmployeeOid))
                            continue;

                        additionalServiceView.MultiEmployeeControlAddServ.SelectedEmployees[i] = new CompactEmployeeDC();
                        additionalServiceView.MultiEmployeeControlAddServ.SelectedEmployees[i] = updatedEmployee;
                    }

                    UpdateSearchViewObjectList(additionalServiceView.MultiEmployeeControlAddServ.employeesearchview,
                        updatedEmployee);

                }
                else if (typeof (T) == typeof (CompactCustomerDC))
                {
                    var updatedCustomer = new CompactCustomerDC();

                    ServiceFacade.DoCustomerServiceSync(
                        s => updatedCustomer = s.GetCompactCustomerDC((updatedObject as CompactCustomerDC).CustomerOid));

                    additionalServiceView.MultiAddServGroupOfPeopleSelectionControl.UpdateCustomers(updatedCustomer);

                    foreach (var item in additionalServiceView.AdditionalServiceBookings.VMList)
                    {
                        var newCustomerList =
                            item.CustomerOidDict.ToDictionary(
                                element =>
                                    element.Key.Equals(updatedCustomer.CustomerOid)
                                        ? updatedCustomer.CustomerOid
                                        : element.Key, element => element.Value);
                        item.CustomerOidDict = newCustomerList;
                    }

                    var containsUpdatedCustomer = false;

                    foreach (var element in from item in additionalServiceView.AdditionalServiceBookings.VMList
                        from element in item.CustomerOidDict
                        where element.Key.Equals(updatedCustomer.CustomerOid)
                        select element)
                        containsUpdatedCustomer = true;

                    if (!containsUpdatedCustomer)
                        return;

                    additionalServiceView.UpdateTeilnahmeGrid();
                }

                #endregion
            }
        }

        private static void UpdateSingleSupportConceptSelectionControl(SingleSupportConceptSelectionControl control, CompactCustomerDC updatedCustomer)
        {
            if (control.SelectedItem.SupportConceptTreeNodeDC == null)
                return;

            var supConSelConSeletedItem = control.SelectedItem;
            
            if (supConSelConSeletedItem != null)
            {
                if (supConSelConSeletedItem.SupportConceptTreeNodeDC.Customer.Equals(updatedCustomer))
                    supConSelConSeletedItem.SupportConceptTreeNodeDC.Customer = updatedCustomer;
                if (supConSelConSeletedItem.SupportConceptTreeNodeDC.SupportConcept.Customer.Equals(updatedCustomer))
                    supConSelConSeletedItem.SupportConceptTreeNodeDC.SupportConcept.Customer = updatedCustomer;
            }

            var newList = control.SearchView.ObjectList;

            foreach (var concept in newList.Where(concept => concept.Customer.Equals(updatedCustomer)))
                concept.Customer = updatedCustomer;

            control.SearchView.ObjectList = newList;
            control.SetSelectedSupportConceptOid(control.SelectedItem.SupportConceptTreeNodeDC.SupportConcept.SupportConceptOid);
            control.UpdateControls();
            control.customerText.Text = updatedCustomer.ToString();
        }

        private static void UpdateLoggedInEmployee(long employeeOid)
        {
            if (employeeOid != BeWoApp.LoggedOnUser.Employee.EmployeeOid) 
                return;

            ServiceFacade.DoEmployeeServiceSync(s => BeWoApp.LoggedOnUser.Employee = s.LoadCompactEmployee(BeWoApp.LoggedOnUser.Employee.EmployeeOid));

            if (BeWoApp.MainControl.HomeButtonPanel == null) 
                return;
            
            BeWoApp.MainControl.HomeView.txtHeader.Text = BeWoApp.LoggedOnUser.Employee.ToString();
        }

        public static void WriteExcelFile(string content, string path)
        {
            using (var uFileStream = File.Create(path))
                using (var uSw = new StreamWriter(uFileStream))
                    uSw.Write(content);

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(path));
        }

		//public static void Richloaded(object sender, RoutedEventArgs e)
		//{
		//    var richEditControl1 = (RichEditControl) sender;
		//    richEditControl1.ActiveViewType = RichEditViewType.Simple;
		//    richEditControl1.ShowBorder = false;
		//    richEditControl1.ShowHoverMenu = false;
		//    richEditControl1.CornerBoxVisibility = Visibility.Visible;
		//    richEditControl1.VerticalRulerVisibility = Visibility.Collapsed;
		//    richEditControl1.HorizontalRulerVisibility = Visibility.Collapsed;
		//    richEditControl1.Language = System.Windows.Markup.XmlLanguage.GetLanguage("de-DE");
		//}

		//public static void Popupmenu(object sender, PopupMenuShowingEventArgs e)
		//{
		//    foreach (var item in e.Menu.ItemLinks.Where(x => x.ActualIsVisible).Where(item => !(item is BarItemLinkSeparator)))
		//    {
		//        var btn = (BarButtonItemLink)item;

		//        if (btn.ActualContent.Equals("Lösche Zeile") ||
		//            btn.ActualContent.Equals("Lösche Spalte") ||
		//            btn.ActualContent.Equals("Lösche Zelle...") ||
		//            btn.ActualContent.Equals("Zellen verbinden") ||
		//            btn.ActualContent.Equals("Teile Zellen...") ||
		//            btn.ActualContent.Equals("Zellausrichtung") ||
		//            btn.ActualContent.Equals("AutoAnpassen") ||
		//            btn.ActualContent.Equals("Tabelleneigenschaften...") ||
		//            btn.ActualContent.Equals("Einzug erhöhen") ||
		//            btn.ActualContent.Equals("Einzug verringern") ||
		//            btn.ActualContent.Equals("Schriftart") ||
		//            btn.ActualContent.Equals("Absatz") ||
		//            btn.ActualContent.Equals("Nummerierun") ||
		//            btn.ActualContent.Equals("Lesezeichen...") ||
		//            btn.ActualContent.Equals("Hyperlink...") ||
		//            btn.ActualContent.Equals("Zeilenumbruch") ||
		//            btn.ActualContent.Equals("Eine Ebene nach vorne") ||
		//            btn.ActualContent.Equals("Eine Ebene nach hinten") ||
		//            btn.ActualContent.Equals("Layout"))
		//            item.IsVisible = false;
		//    }
		//}

        public static void OpenMailClient(string mailAddress, string subject = "")
        {
            var mailCmd = string.Format(@"mailto:{0}?subject={1}", mailAddress, subject);

            System.Diagnostics.Process.Start(mailCmd);
        }
		
		public static bool ValidateServiceRecordVM(ServiceRecordVM vm, SupportConceptStatisticsDC statistics, FlatSupportConceptTreeNodeDC node, bool withoutClient, CompactEmployeeDC selectedEmployee, List<long> employeeOids, List<long> cb2ScOids)
        {
            var lValid = true;

			if (vm.ServiceDescription == null)
			{
				MessageBox.Show("Bitte wählen Sie eine Leistung aus. Sollten keine Leistungen für die gewählte Kategorie verfügbar sein, müssen diese zunächst in der Verwaltung angelegt werden.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
				return false;
			}
			if (vm.GoalTree != null && vm.GoalTree.Count > 0 && (cb2ScOids == null || cb2ScOids.Count < 2))
			{
				if (vm.SelectedGoals.Count == 0 &&
				    MessageBox.Show("Es wurde kein Ziel zugeordnet. Sind Sie sicher, dass Sie speichern möchten?", "Speichern",
					    MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
					return false;
			}

			CompactSupportConceptDC scDc = null;
			CompactOrganisationDC cbDc = null;
			SupportConceptCostBearerRelDC relDc = null;

			if (node != null && node.SupportConceptTreeNodeDC != null)
			{
				scDc = node.SupportConceptTreeNodeDC.SupportConcept;
				cbDc = node.SupportConceptTreeNodeDC.CostBearer;
				relDc = node.SupportConceptTreeNodeDC.SupportConceptCostBearerRelDC;
			}
			

            var dc = vm.CommitToDataContract();
            dc.Employee = selectedEmployee ?? BeWoApp.LoggedOnUser.Employee;
            dc.SupportConcept = scDc;
			dc.CostBearer = cbDc;

            dc.Start = new DateTime(vm.DateAndTime.Value.Year,
                                    vm.DateAndTime.Value.Month,
                                    vm.DateAndTime.Value.Day,
                                    vm.StartTime == null ? vm.DateAndTime.Value.Hour : vm.StartDate.Value.Hour,
                                    vm.StartTime == null ? vm.DateAndTime.Value.Minute : vm.StartDate.Value.Minute,
                                    vm.StartTime == null ? vm.DateAndTime.Value.Second : vm.StartDate.Value.Second);



			if (BeWoApp.AppSettings.IsEndDateVisible)
			{
				if (vm.EndTime.Value.Day != vm.DateAndTime.Value.Day)
				{
					dc.End = vm.EndTime.Value;
				}
				else
				{
					dc.End = dc.Start.Value.AddMinutes(Convert.ToDouble(vm.Duration));
				}
			}
			else
			{
				dc.End = dc.Start.Value.AddMinutes(Convert.ToDouble(vm.Duration));
			}

			
            if (relDc != null)
				dc.CostBearer2SupportConceptOid = relDc.CostBearer2SupportConceptOid;

            var r = new List<ServiceRecordValidationResultDC>();

            var maxdays = BeWoApp.AppSettings.MaxDaysEditServiceRecordsAllowed;

            if (withoutClient && BeWoApp.AppSettings.MaxDaysEditServiceRecordsAllowed <= 0)
                maxdays = -1;

            if (BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowEditAfterMaxDaysInNextMonth))
                maxdays = -1;

	        var test = dc.Start;
	        var test2 = vm.DateAndTime;

			ServiceFacade.DoOperationsServiceSync(o => r = o.ValidateServiceRecord(dc, statistics, maxdays, employeeOids, cb2ScOids));


            if (r.Count > 0)
            {
                var exitLoop = false;
                
                foreach (var result in r)
                {
                    switch (result.ResultType)
                    {
                        case ServiceRecordValidationResult.OutsideOfSupportConcept:
                            MessageBox.Show("Das gewählte Datum '" + vm.DateAndTime.Value.ToShortDateString() + "' liegt außerhalb des Zeitraums des gewählten Hilfeplans (" + relDc.DateRangeString + ").\nDas Speichern ist nicht möglich.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                            lValid = false;
                            exitLoop = true;
                            break;
                        case ServiceRecordValidationResult.OutOfEditLimit:
                            MessageBox.Show("Sie können keine neuen Leistungen für den " + vm.DateAndTime.Value.ToShortDateString() + " dokumentieren, da bereits der " + BeWoApp.AppSettings.MaxDaysEditServiceRecordsAllowed + ". des nachfolgenden Monats überschritten ist.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
                            lValid = false;
                            exitLoop = true;
                            break;
						case ServiceRecordValidationResult.FristAbgelaufen:
							if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecordAllowEditAfterMindays))
							{
								if (BeWoApp.AppSettings.AnzTageZeiterfassErfolgt == 1)
								{
									MessageBox.Show("Sie können keine neuen Leistungen für den " + vm.DateAndTime.Value.ToShortDateString() + " dokumentieren, da die Zeiterfassung innerhalb von einem Tag erfolgen muss.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
								}
								else
								{
									MessageBox.Show("Sie können keine neuen Leistungen für den " + vm.DateAndTime.Value.ToShortDateString() + " dokumentieren, da die Zeiterfassung innerhalb von " + BeWoApp.AppSettings.AnzTageZeiterfassErfolgt + " Tagen erfolgen muss.", "Speichern", MessageBoxButton.OK, MessageBoxImage.Information);
								}

								lValid = false;
								exitLoop = true;
							}
							break;
                        case ServiceRecordValidationResult.Error:
                            MessageBox.Show("Beim Speichern ist ein Fehler aufgetreten.\nDas Speichern ist nicht möglich.", "Speichern nicht möglich", MessageBoxButton.OK, MessageBoxImage.Error);
                            lValid = false;
                            exitLoop = true;
                            break;

                        case ServiceRecordValidationResult.ServiceRecordOverlapping:
							if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreateOverlappingFLS))
                            {
                                MessageBox.Show("An dem gewählten Datum '" + vm.DateAndTime.Value.ToShortDateString() + " " + vm.DateAndTime.Value.ToShortTimeString() + "' existiert bereits ein Eintrag (" + result.Message + " bei Klient/in " + result.CustomerName + ") .\nSpeichern nicht möglich.", "Speichern nicht möglich", MessageBoxButton.OK, MessageBoxImage.Information);
                                lValid = false;
                            }
							else if (MessageBox.Show("An dem gewählten Datum '" + vm.DateAndTime.Value.ToShortDateString() + " " + vm.DateAndTime.Value.ToShortTimeString() + "' existiert bereits ein Eintrag (" + result.Message + " bei Klient/in " + result.CustomerName + ").\nMöchten Sie trotzdem speichern?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                            {
                                lValid = false;
                                exitLoop = true;
                            }
                            break;
                        case ServiceRecordValidationResult.EmployeeOverlapping:
		                   
                            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreateOverlappingFLSForEmployee))
                            {
								MessageBox.Show("An dem gewählten Datum '" + vm.DateAndTime.Value.ToShortDateString() + " " + vm.DateAndTime.Value.ToShortTimeString() + "' existiert bereits ein Eintrag von " + result.EmployeeName + "\n(" + result.Message + ").\nSpeichern nicht möglich.", "Speichern nicht möglich", MessageBoxButton.OK, MessageBoxImage.Information);
                                lValid = false;
                            }
							else if (MessageBox.Show("An dem gewählten Datum '" + vm.DateAndTime.Value.ToShortDateString() + " " + vm.DateAndTime.Value.ToShortTimeString() + "' existiert bereits ein Eintrag von " + result.EmployeeName + "\n(" + result.Message + ").\n\nMöchten Sie trotzdem speichern?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                            {
                                lValid = false;
                                exitLoop = true;
                            }
                            break;
                        case ServiceRecordValidationResult.ApprovedFLSOverspending:
                            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ServiceRecord_AllowCreateMoreFLSThanApproved))
                            {
								MessageBox.Show("Die für diesen Hilfeplan genehmigten FLS (" + (result.ApprovedHours).ToString("N") + ") werden mit diesem Eintrag überschritten. (" + (result.HoursNew).ToString("N") + ").\nSpeichern nicht möglich.", "Speichern nicht möglich", MessageBoxButton.OK, MessageBoxImage.Information);
                                lValid = false;
                            }
							else if (MessageBox.Show("Die für diesen Hilfeplan genehmigten FLS (" + (result.ApprovedHours).ToString("N") + ") werden mit diesem Eintrag überschritten. (" + (result.HoursNew).ToString("N") + ").\nMöchten Sie trotzdem speichern?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                            {
                                lValid = false;
                                exitLoop = true;
                            }
                            break;
                        case ServiceRecordValidationResult.SettlementInvoiceAlreadyExisting:
                            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.BookServiceRecordAfterSettlementInvoice))
                            {
                                MessageBox.Show("Sie können den Eintrag nicht bearbeiten, da bereits eine Spitzabrechnung für diesen Hilfeplan erstellt wurde.", "Speichern nicht möglich", MessageBoxButton.OK, MessageBoxImage.Warning);
                                lValid = false;
                            }
							else if (MessageBox.Show("Es existiert bereits eine Spitzabrechnung. Um diesen Eintrag zu berücksichtigen, muss eventuell eine neue Spitzabrechnung erstellt werden.\nMöchten Sie trotzdem speichern?", "Speichern", MessageBoxButton.YesNo, MessageBoxImage.Warning).Equals(MessageBoxResult.No))
                            {
                                lValid = false;
                                exitLoop = true;
                            }
                            break;
						case ServiceRecordValidationResult.Custom:
							MessageBox.Show(result.Message, "Speichern nicht möglich", MessageBoxButton.OK, MessageBoxImage.Error);
							lValid = false;
							exitLoop = true;
							break;
                    }

                    if (exitLoop) break;
                }
            }
            
            return lValid;
        }

		/// <summary>
		/// Erzeugt einen Report mit Hilfe des ReportServices und zeigt ihn in einem BeWoWindow
		/// </summary>
		/// <param name="title">Titel des Fensters</param>
		/// <param name="documentPreview">Documentpreview für den Report</param>
		/// <param name="variablen">Dictionary mit Variablen für das ReportObject</param>
		/// <param name="reportType">Der Typ des Reports (z.B. KalenderMonatsformatReport)</param>
		public static void ShowReport(string title, DocumentPreview documentPreview, Dictionary<String, Object> variablen, ReportEnum reportType)
	    {
			switch (reportType)
			{
				case ReportEnum.KalenderMonatsReportEnum:
					var appointmentIds     = (List<long>)variablen["appointmentOidListe"];
					var selectedDays       = (List<DateTime>)variablen["datesList"];
					var employeeOid        = Convert.ToInt64(variablen["employeeOid"]);
					var serienTermine      = (List<SchedulerAppointmentDC>)variablen["serienTermine"];
					var mehrtaegigeTermine = (List<SchedulerAppointmentDC>)variablen["mehrtaegigeTermine"];

					ServiceFacade.DoReportServiceAsync(strom => strom.CreateKalenderReport(appointmentIds, employeeOid, serienTermine, selectedDays, mehrtaegigeTermine),
						ms => BeWoApp.MainControl.Dispatch(() => ShowReportWindow(ms, documentPreview, title)));
					break;
				case ReportEnum.KassenbuchReportEnum:
					var zeitraum      = (DateTime) variablen["zeitraum"];
                    var objectOid     = Convert.ToInt64(variablen["objectoid"]);
			        var objectTid     = (TableID) Enum.Parse(typeof (TableID), variablen["objecttid"].ToString());

			        var kasse = (BargeldkassenDC) variablen["bargeldkasse"];

                    ServiceFacade.DoReportServiceAsync(strom => strom.CreateKassenbuchReport(zeitraum, kasse, objectOid, objectTid), ms => BeWoApp.MainControl.Dispatch(() => ShowReportWindow(ms, documentPreview, title)));

					break;
				case ReportEnum.ZahlungsbelegEnum:
					var transaktion = (BargeldtransaktionDC) variablen["transaktion"];
                    var objectOid2  = Convert.ToInt64(variablen["objectoid"]);
                    var objectTid2  = (TableID) Enum.Parse(typeof(TableID), variablen["objecttid"].ToString());

					ServiceFacade.DoReportServiceAsync(strom => strom.CreateKassenbelegReport(transaktion, objectOid2, objectTid2), ms => BeWoApp.MainControl.Dispatch(() => ShowReportWindow(ms, documentPreview, title)));

					break;
			}
	    }

	    public static void ShowReportWindow(MemoryStream ms, DocumentPreview documentPreview, String title)
	    {
			var report = new XtraReport();
			try
			{
				var scrollablePageView = (IScrollInfo)LayoutHelper.FindElement(documentPreview,
					p => p.GetType() == typeof(DevExpress.Xpf.Printing.Native.ScrollablePageView
						));
				if (scrollablePageView != null)
					scrollablePageView.PageUp();
				report.PrintingSystem.LoadDocument(ms);

			}
			catch (Exception)
			{
				var msg = System.Text.Encoding.ASCII.GetString(ms.ToArray());

				MessageBox.Show("Beim Öffnen der Druckvorschau ist leider ein Fehler aufgetreten!\n\n" + msg, "Fehler",
					MessageBoxButton.OK, MessageBoxImage.Exclamation);
			}
			ms.Close();
			ms.Dispose();

			report.DefaultPrinterSettingsUsing.UseLandscape = BeWoApp.AppSettings.PrinterSettingsUseLandscape;
			report.DefaultPrinterSettingsUsing.UseMargins = BeWoApp.AppSettings.PrinterSettingsUseMargins;
			report.DefaultPrinterSettingsUsing.UsePaperKind = BeWoApp.AppSettings.PrinterSettingsUsePaperKind;

			BeWoWindow window = null;

			DocumentPreview dp = documentPreview;
			if (dp == null)
			{
				dp = new DocumentPreview();
				window = new BeWoWindow { GroupBoxContent = dp, Owner = BeWoApp.CurrentBeWo.MainWindow };
				ThemeManager.SetTheme(window, Theme.Office2010Black);
			}
            dp.Model = new ReportPreviewModelLandscapeBugWorkaround(report);
			ThemeManager.SetTheme(dp, Theme.Office2007Black);

			dp.BarManager.Loaded += delegate
			{
				dp.BarManager.Items["documentMap"].IsVisible = false;
				dp.BarManager.Items["open"].IsVisible = false;
				dp.BarManager.Items["email"].IsVisible = false;
				dp.BarManager.Items["watermark"].IsVisible = false;
				dp.BarManager.Items["pageSetup"].IsVisible = false;
				dp.BarManager.Items["scaling"].IsVisible = false;
				dp.BarManager.Items["save"].IsVisible = false;
				dp.BarManager.Items["printDirect"].IsVisible = false;
				dp.BarManager.Items["exportText"].IsVisible = false;
				dp.BarManager.Items["exportCSV"].IsVisible = false;
				dp.BarManager.Items["exportMHT"].IsVisible = false;
				dp.BarManager.Items["exportXPS"].IsVisible = false;
				var item = dp.BarManager.Items["exportRTF"];
			};
			if (window != null)
			{
				window.rootGroupBox.Header = String.IsNullOrEmpty(title) ? "Druckvorschau" : title;
				window.Title = "Druckvorschau";
				window.Show();
			}

			dp.Visibility = Visibility.Visible;

			BeWoApp.MainControl.EndWaiting();
	    }
    }
}
