using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;

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

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

using DevExpress.Utils;
using DevExpress.Xpf.Editors.Settings;
using DevExpress.Xpf.Grid;
using DevExpress.XtraGrid;

using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Media;

using CheckBox          = System.Windows.Controls.CheckBox;
using Hyperlink         = System.Windows.Documents.Hyperlink;
using VerticalAlignment = System.Windows.VerticalAlignment;


namespace BeWo.View.Detail
{
    public partial class CustomerView
    {
        private Dictionary<int, SystemEntryID>            _AssessmentSheetCategory2SystemEntryID;
        private BindingList<KeyValuePair<string, string>> _ChoosenDiagnosis;
        private StringBuilder                             _LogText;

        private OrganisationView _OrganisationModalPopUp;
        private PersonView       _PersonModalPopUp;

        private BindingList<KeyValuePair<string, string>> _PossibleDiagnosis;

        private CustomerVM _ViewModel;
        private bool       _saveInProgress;

        private GridControl grid_aktuellemvl;
        private GridControl grid_AbsenceTimes;
        private GridControl grid_EmployeeRelation;
        private GridControl grid_Organisations;
        private GridControl grid_Persons;
        private GridControl grid_TeamRelation;
        private GridControl grid_Medikamentenverordnung;
        private GridControl grid_bedarfsmvl;
        private GridControl grid_costBearers;

        public static bool DarfBargeldtransaktionenBearbeiten
        {
            get { return BeWoApp.LoggedOnUser.HasRight(UserRightType.BargeldverwaltungBearbeiten); }
        }

        public static DefaultBoolean BargeldtransaktionenBearbeitenAlsDefaultBooelan
        {
            get { return (DefaultBoolean)(Convert.ToInt32(BeWoApp.LoggedOnUser.HasRight(UserRightType.BargeldverwaltungBearbeiten)) + 1); }
        }

        public static readonly string[] GradDerBehinderungComboBoxQuelle = { "20", "30", "40", "50", "60", "70", "80", "90", "100" };

        //Konstruktor
        public CustomerView(CustomerVM pCustomerVM)
        {
            InitializeComponent();

            BehinderungsartenSelection.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, (s, e) => this.Dispatch(() => { PopupBehinderungsarten.IsOpen = false; })));
            MerkzeichenSelection.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, (s, e) => this.Dispatch(() => { PopupMerkzeichen.IsOpen = false; })));

            AdditionalServiceAssessmentSheetCategories = new List<AssessmentSheetCategoryDC>();

            if (BeWoApp.LoggedOnUser.HasRight(UserRightType.BargeldverwaltungNurEigeneAnsehen) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.BargeldverwaltungAnsehen))
            {
                tabitem_Bargeldverwaltung.Visibility = pCustomerVM.IsNew || BeWoApp.LoggedOnEmployee.RelatedCustomers.Any(a => a.Customer.CustomerOid.Equals(pCustomerVM.CommitToDataContract().CustomerOid.Value)) ? Visibility.Visible : Visibility.Collapsed;
            }

            if (ShouldLog)
            {
                _LogText = new StringBuilder();
                tabitem_log.Visibility = Visibility.Visible;
            }
            else
            {
                tabitem_log.Visibility = Visibility.Collapsed;
            }

            ViewModel = pCustomerVM;

			if (pCustomerVM.VarFields == null || pCustomerVM.VarFields.VMList.Count == 0)
			{
				tabitem_varFields.Visibility = Visibility.Collapsed;
			}
			if (!BeWoApp.AppSettings.ShowLargeCustomerNotice)
			{
				tabitem_notice.Visibility = Visibility.Collapsed;
			}
			if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.DocumentsAllowViewAll) && !BeWoApp.LoggedOnUser.HasRight(UserRightType.DokumenteKlienten))
			{
				tabitem_documents.Visibility = Visibility.Collapsed;
			}

            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.ChatSettings))
            {
                tabitem_chatservice.Visibility = Visibility.Collapsed;
            }


            // HACK: Force the devexpress grid to end editing when the mouse is over savebutton
			// by setting the focus to another element. 
			MouseMove += (s, e) =>
			{
				if ((grid_AbsenceTimes     == null || !grid_AbsenceTimes.IsVisible) &&
				    (grid_EmployeeRelation == null || !grid_EmployeeRelation.IsVisible) &&
				    (grid_TeamRelation     == null || !grid_TeamRelation.IsVisible) &&
				    (grid_costBearers      == null || !grid_costBearers.IsVisible) &&
				    (grid_Persons          == null || !grid_Persons.IsVisible) &&
				    (grid_Organisations    == null || !grid_Organisations.IsVisible))
				{
					return;
				}

//<<<<<<< .mine
//            if (!BeWoApp.AppSettings.ShowLargeCustomerNotice)
//            {
//                tabitem_notice.Visibility = Visibility.Collapsed;
//            }

//            // HACK: Force the devexpress grid to end editing when the mouse is over savebutton
//            // by setting the focus to another element. 
//            MouseMove += (s, e) =>
//            {
//                if ((grid_AbsenceTimes         == null || !grid_AbsenceTimes.IsVisible) &&
//                    (grid_EmployeeRelation     == null || !grid_EmployeeRelation.IsVisible) &&
//                    (grid_TeamRelation         == null || !grid_TeamRelation.IsVisible) &&
//                    (grid_costBearers          == null || !grid_costBearers.IsVisible) &&
//                    (grid_Persons              == null || !grid_Persons.IsVisible) &&
//                    (grid_Organisations        == null || !grid_Organisations.IsVisible))
//                {
//                    return;
//                }

//||||||| .r8680
//            if (!BeWoApp.AppSettings.ShowLargeCustomerNotice)
//            {
//                tabitem_notice.Visibility = Visibility.Collapsed;
//            }

//            // HACK: Force the devexpress grid to end editing when the mouse is over savebutton
//            // by setting the focus to another element. 
//            MouseMove += (s, e) =>
//            {
//                if ((grid_AbsenceTimes         == null || !grid_AbsenceTimes.IsVisible) &&
//                    (grid_EmployeeRelation     == null || !grid_EmployeeRelation.IsVisible) &&
//                    (grid_TeamRelation         == null || !grid_TeamRelation.IsVisible) &&
//                    (grid_costBearers          == null || !grid_costBearers.IsVisible) &&
//                    (grid_Persons              == null || !grid_Persons.IsVisible) &&
//                    (grid_Organisations        == null || !grid_Organisations.IsVisible)
//                    //&& (grid_bargeldtransaktionen == null || !grid_bargeldtransaktionen.IsVisible)
//                    )
//                {
//                    return;
//                }

//=======
//>>>>>>> .r8712
                var p = e.GetPosition(btnSave);
                if (p.X >= 0 && p.X < btnSave.ActualWidth && p.Y >= 0 && p.Y < btnSave.ActualHeight)
                {
                    var i = tabroot.Focus();
                }
            };

            txtDistance.Visibility = BeWoApp.AppSettings.ShowCustomerDistanceFields ? Visibility.Visible : Visibility.Collapsed;
            lblDistance.Visibility = BeWoApp.AppSettings.ShowCustomerDistanceFields ? Visibility.Visible : Visibility.Collapsed;

            InitCustomerCareTypeList();

            panelDebitor.Visibility        = BeWoApp.AppSettings.ShowDatevFields ? Visibility.Visible : Visibility.Collapsed;
            ctrlAdvisedAttended.Visibility = BeWoApp.AppSettings.ShowAdvisedAttendedFlag ? Visibility.Visible : Visibility.Collapsed;
            txtDebitorNumber.Visibility    = lblDebitorNumber.Visibility;

            if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Customer_AllowArchiving))
            {
                lblArchiviert.Visibility = Visibility.Hidden;
                chkArchiviert.Visibility = Visibility.Hidden;
            }

            groupbox_Environment.Visibility = BeWoApp.Mandator.BeWoClientType == 8 ? Visibility.Visible : Visibility.Collapsed;

            InitDiagnosisLists();

            if (!BeWoApp.AppSettings.IsMedicationAllowed)
                tabitem_Medikamentenverordnungen.Visibility = Visibility.Collapsed;

            var l = new List<int>();
            for (var i = 9; i >= 0; i--)
            {
                l.Add(DateTime.Now.Year - i);
            }

            GdBComboBox.ItemsSource   = GradDerBehinderungComboBoxQuelle;
            GdBComboBox.SelectedIndex = GdBComboBox.Items.IndexOf(ViewModel.GradDerBehinderung);

            MerkzeichenSelection.MerkzeichenSourceListe             = ViewModel.MerkzeichenListe;
            BehinderungsartenSelection.BehinderungsartenSourceListe = ViewModel.BehinderungsartenListe;

            Log("Klient geöffnet");

            if (_ViewModel.CustomerImage != null)
            {
                var biImg = new BitmapImage();
                var ms    = new MemoryStream(_ViewModel.CustomerImage);

                biImg.BeginInit();
                biImg.StreamSource = ms;
                biImg.EndInit();

                var imgSrc = biImg as ImageSource;

                Img.Source = biImg;
            }

            Img.EditValueChanged += Image_EditValueChanged;
        }

        void Image_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            _ViewModel.CustomerImage = Img.EditValue as byte[];
        }

        public List<AssessmentSheetCategoryDC> AdditionalServiceAssessmentSheetCategories { get; set; }

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

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

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

        internal CustomerVM ViewModel
        {
            get { return _ViewModel; }

            set
            {
                _ViewModel = value;
                root.DataContext = value;

                if (string.IsNullOrEmpty(ViewModel.ICD10Diagnosis))
                {
                    lbl_diag10.Visibility = Visibility.Collapsed;
                    tb_diag10.Visibility = Visibility.Collapsed;
                }

                Log(String.Format("ViewModel gesetzt. DataContext={0}", root.DataContext));

                if (_ViewModel != null && ShouldLog)
                {
                    _ViewModel.EnableLogging(true, _LogText);
                }

                _saveInProgress = false;
            }
        }

        public CustomerVM PublicViewModel { get { return _ViewModel; } }

        public static bool ShouldLog
        {
			get { return false; } // BeWoApp.Tenant == "1549622397" && BeWoApp.UserName.ToLower() == "h.krause"; }
            //get { return BeWoApp.Tenant == "demo" && BeWoApp.UserName == "demo"; }
        }

        private void Log(string log)
        {
            if (ShouldLog)
            {
                if (_LogText == null)
                {
                    _LogText = new StringBuilder();
                }

                if (_LogText.Length > 0)
                {
                    _LogText.Append("\n");
                }

                _LogText.Append(log);
            }
        }

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

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

        protected override UserRightType[] GetSaveDemands()
        {
            return ViewModel.IsNew ? new[] { UserRightType.CreateAll, UserRightType.CustomerView_Create } : new[] { UserRightType.EditAll, UserRightType.CustomerView_Edit };
        }

        protected override void Save()
        {
            if (!_saveInProgress)
            {
                _saveInProgress = true;
                var lDataContract = ViewModel.CommitToDataContract();
                try
                {
                    if (ViewModel.IsNew)
                    {
                        IsDoneWithInsertOrUpdate = false;
                        ServiceFacade.DoCustomerServiceAsync(s => s.InsertNewCustomer(lDataContract), ReloadViewModel);
                    }
                    else
                    {
                        IsDoneWithInsertOrUpdate = false;
                        ServiceFacade.DoCustomerServiceAsync(s => s.UpdateCustomer(lDataContract), ReloadViewModel);
                    }

                    Cache.GetInstance().ClearSupportConceptTree();
                    Cache.GetInstance().ClearCustomers();
                    BeWoApp.MainControl.ResetView(UIContext.Customer);

                }
                catch (FaultException<BeWoFault>)
                {
                    MessageBox.Show(
                        "Dieser Datensatz wurde in der Zwischenzeit von einem anderen Benutzer geändert. Klicken Sie Ok um den Datansatz erneut zu laden. Ihre Änderungen gehen dabei leider verloren.");
                    ReloadViewModel(lDataContract.CustomerOid.Value);
                }
            }
        }

        private void Button_deleteCostBearerClick(object sender, RoutedEventArgs e)
        {
            ViewModel.CostBearers.VMList.Remove(grid_costBearers.GetCurrentValue<CustomerCostBearerRealtionVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_costBearers);
        }

        private void EmployeeSearchView_ItemSelected_1(object sender, EventArgs<CompactEmployeeDC> e)
        {
            popup_employee.IsOpen = false;
            ViewModel.EmployeeRelations.NewVM.Employee = e.Data;
            popupedit_employeeRelations.Focus();
        }

        private void TeamSearchView_ItemSelected_1(object sender, EventArgs<CompactTeamDC> e)
        {
            popup_team.IsOpen = false;
            ViewModel.TeamRelations.NewVM.Team = e.Data;
            popupedit_teamRelations.Focus();
        }

        private void InitCustomerCareTypeList()
        {
            foreach (var dc in ViewModel.PossibleCustomerCareTypes)
            {
                var chkBox = new CheckBox { IsChecked = ViewModel.CustomerCareTypes.Contains(dc), Content = dc };
                chkBox.Checked += (s, e) =>
                {
                    var cb = (CheckBox)s;
                    ViewModel.CustomerCareTypes.Add((ValueListEntryDC)cb.Content);
                };
                chkBox.Unchecked += (s, e) =>
                {
                    var cb = (CheckBox)s;
                    ViewModel.CustomerCareTypes.Remove((ValueListEntryDC)cb.Content);
                };
                customerCareTypeList.Items.Add(chkBox);
            }
        }

        private void InitDiagnosisLists()
        {
            var gb = tabitem_diagnosis.Resources["gb_possible"] as GroupBox;
            var c = (gb.Content as Grid).FindFirstVisualChild<GridControl>();

            _PossibleDiagnosis = new BindingList<KeyValuePair<string, string>>(new List<KeyValuePair<string, string>>(BeWoApp.ICD10Diagnosis));
            _ChoosenDiagnosis = new BindingList<KeyValuePair<string, string>>();

            var ch = ViewModel.ICD10Codes.Select(code => new KeyValuePair<string, string>(code, BeWoApp.ICD10Diagnosis[code])).ToList();

            _ChoosenDiagnosis.AddRange(ch);
            _PossibleDiagnosis.RemoveRange(ch);

            grid_choosenDiagnosis.ItemsSource = _ChoosenDiagnosis;
            c.ItemsSource = _PossibleDiagnosis;
        }

        private void ReloadViewModel(long pCustomerOID)
        {
            // reload to update version information and oid
            VMFactory.CreateCustomerVMAsync(pCustomerOID, cb => this.Dispatch(delegate { ViewModel = cb; UpdateUris(); }));

            if (ModalEditViewUpdateCallback != null)
            {
                ModalEditViewUpdateCallback();
            }

            IsDoneWithInsertOrUpdate = true;
        }

        public void ReloadViewModel()
        {
            ReloadViewModel(ViewModel.DataContract.CustomerOid.Value);
        }

        private void TabItemAbsenceTimes_Selected(object sender, RoutedEventArgs e)
        {
            if (grid_AbsenceTimes != null) return;

            grid_AbsenceTimes = root.Resources["datagrid_absences"] as GridControl;

            GroupBoxAbsenceTimes.Content = grid_AbsenceTimes;

            if (ViewModel.AbsenceTimes != null && grid_AbsenceTimes != null)
                grid_AbsenceTimes.Columns["Reason"].EditSettings = new ComboBoxEditSettings { ItemsSource = ViewModel.AbsenceTimes.PossibleReasons };
        }

        // private void ComboBox_Loaded(object sender, RoutedEventArgs e)
        // {
        // ((ComboBox)sender).ItemTemplateSelector = new ComboBoxTemplateSelector((ComboBox)sender);
        // ((ComboBox)sender).ItemsSource = ViewModel.AbsenceTimes.PossibleReasons;
        // }

        private void TabItemCostBearer_Selected(object sender, RoutedEventArgs e)
        {
            if (grid_costBearers == null)
            {
                grid_costBearers = root.Resources["grid_costBearer"] as GridControl;
                GroupBoxCostBearerGrid.Content = grid_costBearers;
            }
        }

        private void TabItemEmployees_Selected(object sender, RoutedEventArgs e)
        {
            if (grid_EmployeeRelation == null)
            {
                grid_EmployeeRelation = root.Resources["datagrid_EmployeeRelation"] as GridControl;

                Grid.SetRow(grid_EmployeeRelation, 1);
                employeeGrid.Children.Add(grid_EmployeeRelation);

                if (ViewModel.EmployeeRelations != null)
                {
                    grid_EmployeeRelation.Columns["Role"].EditSettings = new ComboBoxEditSettings { ItemsSource = ViewModel.EmployeeRelations.PossibleRoles };
                }
            }
            if (grid_TeamRelation == null)
            {
                grid_TeamRelation = root.Resources["datagrid_TeamRelation"] as GridControl;

                Grid.SetRow(grid_TeamRelation, 1);
                teamGrid.Children.Add(grid_TeamRelation);

                //if (ViewModel.TeamRelations != null)
                //    grid_TeamRelation.Columns["Role"].EditSettings = new ComboBoxEditSettings { ItemsSource = ViewModel.EmployeeRelations.PossibleRoles };
            }
        }

        private void TabItemPersons_Selected(object sender, RoutedEventArgs e)
        {
            if (grid_Persons == null)
            {
                grid_Persons = root.Resources["grid_PersonRelations"] as GridControl;

                Grid.SetRow(grid_Persons, 1);
                environmentPersonGrid.Children.Add(grid_Persons);

                if (ViewModel.EnvironmentPersons != null)
                {
                    grid_Persons.Columns["Role"].EditSettings = new ComboBoxEditSettings { ItemsSource = ViewModel.EnvironmentPersons.PossibleRoles };
                }
            }

            if (grid_Organisations == null)
            {
                grid_Organisations = root.Resources["grid_OrganisationRelations"] as GridControl;

                Grid.SetRow(grid_Organisations, 1);
                environmentOrganisationGrid.Children.Add(grid_Organisations);

                if (ViewModel.EnvironmentOrganisations != null)
                {
                    grid_Organisations.Columns["Role"].EditSettings = new ComboBoxEditSettings { ItemsSource = ViewModel.EnvironmentOrganisations.PossibleRoles };
                }
            }
        }

        private void UserControl_GotFocus(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource.Equals(this))
            {
                textbox_first.Focus();
            }
        }

        private void _PersonModalPopUp_PersonSavedOrUpdated(object sender, EventArgs<PersonVM> e)
        {
            ServiceFacade.DoCustomerServiceAsync(
                s => s.LoadPersonCompact(e.Data.DataContract.PersonOid.Value),
                p => this.Dispatch(
                    delegate
                    {
                        MainControl.CloseCurrentPopUp();
                        BeWoUtils.UpdateAllViews(p);
                        ViewModel.EnvironmentPersons.NewVM.Person = p;
                        popup_newEnvironmentPerson.IsOpen = true;
                        popupedit_environmentPersonSearch.Focus();
                    }));
        }

        private void _OrganisationModalPopUp_OrganisationSavedOrUpdated(object sender, EventArgs<OrganisationVM> e)
        {
            ServiceFacade.DoCustomerServiceAsync(
                s => s.LoadOrganisationCompact(e.Data.DataContract.OrganisationOid.Value),
                p => this.Dispatch(
                    delegate
                    {
                        MainControl.CloseCurrentPopUp();
                        BeWoUtils.UpdateAllViews(p);
                        ViewModel.EnvironmentOrganisations.NewVM.Organisation = p;
                        popup_newEnvironmentOrganisation.IsOpen = true;
                        popupedit_environmentOrganisationSearch.Focus();


                    }));
        }

        private void button_addAbsence_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTrigger.Validate(groupbox_newAbsenceTime))
            {
                ViewModel.AbsenceTimes.AddNewVMToList();
            }
        }

        private void button_addCostBearer_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTrigger.Validate(groupBox_newCostBearer))
            {
                ViewModel.CostBearers.AddNewVMToList();
            }
        }

        private void button_addDiagnosos_Click(object sender, RoutedEventArgs e)
        {
            var gb = tabitem_diagnosis.Resources["gb_possible"] as GroupBox;
            var c = (gb.Content as Grid).FindFirstVisualChild<GridControl>();

            c.Width = grid_choosenDiagnosis.ActualWidth;

            c.FilterString = string.Empty;
            c.View.FocusedRowHandle = DataControlBase.AutoFilterRowHandle;
            (c.View as TableView).FocusedColumn = c.Columns[1];

            // var t =  c.View.GetCellElementByRowHandleAndColumn(GridControl.AutoFilterRowHandle, c.Columns[1]);
            MainControl.ShowControlAsModalPopUp(gb, HorizontalAlignment.Center, VerticalAlignment.Top);
        }

        private void button_addDisability_Click(object sender, RoutedEventArgs e)
        {
            var lDisability = listbox_possibleDisabilities.SelectedItem as ValueListEntryDC;
            ViewModel.PossibleDisabilities.Remove(lDisability);
            ViewModel.Disabilities.Add(lDisability);
            ViewModel.Disabilities.Sort();
        }

        private void button_addEmployeeRelation_Click(object sender, RoutedEventArgs e)
        {

            if (ValidationTrigger.Validate(groupbox_newEmployeeRel))
            {
                popup_newEmployeeRel.IsOpen = false;
                ViewModel.EmployeeRelations.AddNewVMToList();
            }
        }

        private void button_cancelEmployeeRelation_Click(object sender, RoutedEventArgs e)
        {
            popup_newEmployeeRel.IsOpen = false;
        }

        private void button_addTeamRelation_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTrigger.Validate(groupbox_newTeamRel))
            {
                popup_newTeamRel.IsOpen = false;
                ViewModel.TeamRelations.AddNewVMToList();
            }
        }

        private void button_cancelTeamRelation_Click(object sender, RoutedEventArgs e)
        {

            popup_newTeamRel.IsOpen = false;
        }

        private void button_addEnvironmentPerson_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTrigger.Validate(groupbox_newEnvironmentPerson))
            {
                popup_newEnvironmentPerson.IsOpen = false;
                ViewModel.EnvironmentPersons.AddNewVMToList();
            }
        }

        private void button_cancelAddEnvironmentPerson_Click(object sender, RoutedEventArgs e)
        {
            popup_newEnvironmentPerson.IsOpen = false;
        }

        private void button_addEnvironmentOrganisation_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTrigger.Validate(groupbox_newEnvironmentOrganisation))
            {
                popup_newEnvironmentOrganisation.IsOpen = false;
                ViewModel.EnvironmentOrganisations.AddNewVMToList();
            }
        }

        private void button_cancelAddEnvironmentOrganisation_Click(object sender, RoutedEventArgs e)
        {

            popup_newEnvironmentOrganisation.IsOpen = false;
        }

        private void button_addPlacement_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.PlacementList.NewVM.PlacementDate = DateTime.Now.Date;
            ViewModel.PlacementList.AddNewVMToList();
        }

        private void button_deletePlacement_Click(object sender, RoutedEventArgs e)
        {
            var btn = (Button)sender;

            var vm = btn.DataContext as PlacementVM;
            if (vm != null)
            {
                ViewModel.PlacementList.VMList.Remove(vm);
            }
        }

        private void button_environmentPersonDeleteClick(object sender, RoutedEventArgs e)
        {
            ViewModel.EnvironmentPersons.VMList.Remove(grid_Persons.GetCurrentValue<CustomerPersonRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_Persons);
        }

        private void button_environmentOrganisationDeleteClick(object sender, RoutedEventArgs e)
        {
            ViewModel.EnvironmentOrganisations.VMList.Remove(grid_Organisations.GetCurrentValue<CustomerOrganisationRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_Organisations);
        }

        private void button_removeAbsence_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.AbsenceTimes.VMList.Remove(grid_AbsenceTimes.GetCurrentValue<AbsenceTimeVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_AbsenceTimes);
        }

        private void button_removeDiagnosis_Click(object sender, RoutedEventArgs e)
        {
            var item = _ChoosenDiagnosis.First(i => i.Key.Equals(((Control)sender).Tag));
            _ChoosenDiagnosis.Remove(item);
            ViewModel.ICD10Codes.Remove(item.Key);
            _PossibleDiagnosis.Add(item);
            _PossibleDiagnosis.Sort((x, y) => x.Key.CompareTo(y.Key));
        }

        private void button_removeDisability_Click(object sender, RoutedEventArgs e)
        {
            var lDisability = listbox_disabilities.SelectedItem as ValueListEntryDC;
            ViewModel.Disabilities.Remove(lDisability);
            ViewModel.PossibleDisabilities.Add(lDisability);
            ViewModel.PossibleDisabilities.Sort();
        }

        private void button_removeEmployeeRelation_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.EmployeeRelations.VMList.Remove(grid_EmployeeRelation.GetCurrentValue<CustomerEmployeeRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_EmployeeRelation);
        }

        private void button_removeTeamRelation_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.TeamRelations.VMList.Remove(grid_TeamRelation.GetCurrentValue<CustomerTeamRelationVM>());
            BeWoWpfUtils.RefreshDXGrid(grid_TeamRelation);
        }

        private void comboBox_PlacementObjectives_Loaded(object sender, RoutedEventArgs e)
        {
            var cb = sender as ComboBox;
            var obj = cb.GetBindingExpression(ItemsControl.ItemsSourceProperty);

            if (obj == null)
            {
                cb.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("PlacementObjectives") { Source = ViewModel, });
            }
        }

        private void costbearersearchview_ItemSelected(object sender, EventArgs<CompactOrganisationDC> e)
        {
            popup_costBearer.IsOpen = false;
            ViewModel.CostBearers.NewVM.CostBearer = e.Data;
            popup_costBearer.Focus();
        }

        private void grid_possibleDiagnosis_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var grid = sender as GridControl;
            int rowHandle = grid.View.GetRowHandleByMouseEventArgs(e);
            if (rowHandle != DataControlBase.InvalidRowHandle && grid.GetRow(rowHandle) != null)
            {
                var item = (KeyValuePair<string, string>)grid.GetRow(rowHandle);
                _PossibleDiagnosis.Remove(item);
                _ChoosenDiagnosis.Add(item);
                ViewModel.ICD10Codes.Add(item.Key);
                MainControl.CloseCurrentPopUp();
            }
        }

        private void personsearchview_EnvironmentPersonSelected(object sender, EventArgs<CompactPersonDC> e)
        {
            popup_person.IsOpen = false;
            personsearchview.ItemSelected -= personsearchview_EnvironmentPersonSelected;
            ViewModel.EnvironmentPersons.NewVM.Person = e.Data;
            popupedit_environmentPersonSearch.Focus();
        }

        private void organisationsearchview_EnvironmentOrganisationSelected(object sender, EventArgs<CompactOrganisationDC> e)
        {
            popup_organisation.IsOpen = false;
            organisationsearchview.ItemSelected -= organisationsearchview_EnvironmentOrganisationSelected;
            ViewModel.EnvironmentOrganisations.NewVM.Organisation = e.Data;
            popupedit_environmentOrganisationSearch.Focus();
        }

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

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

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

        private void popupedit_environmentPersonSearch_NewClick(object sender, RoutedEventArgs e)
        {
            popup_newEnvironmentPerson.IsOpen = false;
            VMFactory.CreatePersonVMAsync(
                cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<PersonVM, PersonDC, CustomerView>(cb, this,
                    () => this.Dispatch(delegate { }), personSavedOrUpdated: _PersonModalPopUp_PersonSavedOrUpdated)));
        }

        private void popupedit_environmentOrganisationSearch_NewClick(object sender, RoutedEventArgs e)
        {
            popup_newEnvironmentOrganisation.IsOpen = false;
            VMFactory.CreateOrganisationVMAsync(
                cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<OrganisationVM, OrganisationDC, CustomerView>(cb, this,
                    () => this.Dispatch(delegate { }), _OrganisationModalPopUp_OrganisationSavedOrUpdated)));
        }

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

        private void popupedit_environmentOrganisationSearch_PopUpClick(object sender, RoutedEventArgs e)
        {
            organisationsearchview.ItemSelected += organisationsearchview_EnvironmentOrganisationSelected;
            popup_organisation.IsOpen = true;
        }

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

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

        private void tabitem_chatservice_Selected(object sender, RoutedEventArgs e)
        {
            if (tabitem_chatservice.Content == null)
            {
                tabitem_chatservice.Content = new ChatServiceCustomer(TableID.Customer, ViewModel.DataContract.CustomerOid.Value);
            }
        }

        private void tabitem_log_Selected(object sender, RoutedEventArgs e)
        {
            if (ShouldLog)
            {
                var txt = tabitem_log.Content as TextBlock;

                if (txt == null)
                {
                    txt = new TextBlock();
                    tabitem_log.Content = txt;
                }

                if (_LogText != null)
                {
                    txt.Text = _LogText.ToString();
                }
            }
        }

        //Scheduler
        //private void tabitem_scheduler_Selected(object sender, RoutedEventArgs e)
        //{
        //    if (this.ViewModel.IsNew)
        //    {
        //        MessageBox.Show("Bevor Sie zu einem neuen Klienten Termine anlegen können, muss dieser gespeichert werden.", "Erst speichern bitte", MessageBoxButton.OK, MessageBoxImage.Information);
        //        return;
        //    }

        //    if (this.tabitem_scheduler.Content == null)
        //    {
        //        SchedulerFilter filter = new SchedulerFilter();
        //        filter.CustomerOid = this.ViewModel.DataContract.CustomerOid;

        //        this.tabitem_scheduler.Content = new SchedulerView(AppointmentKind.Customer, filter, 3);
        //    }
        //}

        private void DeleteIndAscButton_Click(object sender, RoutedEventArgs e)
        {
            var lVM = datagrid_asc.GetCurrentValue<AssessmentSheetCategoryVM>();
            if (lVM == null)
            {
                return;
            }

            ViewModel.IndividualAssessmentSheetCategories.VMList.Remove(lVM);
            BeWoWpfUtils.RefreshDXGrid(datagrid_asc);
        }

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

            if (data == null || data.RowHandle == null)
            {
                return;
            }

            var vm = datagrid_asc.GetRow(data.RowHandle.Value) as AssessmentSheetCategoryVM;

            if (vm == null)
            {
                return;
            }

            ViewModel.IndividualAssessmentSheetCategories.PossibleValues.ForEach(i => i.IsEditSelected = vm.Values.Exists(j => j.AssessmentSheetValueOid.Equals(i.AssessmentSheetValueOid)));
            ViewModel.IndividualAssessmentSheetCategories.EditVM = vm;
            popup_values.IsOpen = true;
        }

        private void button_addIndAsc_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.IndividualAssessmentSheetCategories.NewVM.Values = ViewModel.IndividualAssessmentSheetCategories.PossibleValues.Where(i => i.IsNewSelected).ToList();
            ViewModel.IndividualAssessmentSheetCategories.PossibleValues.ForEach(i => i.IsNewSelected = false);
            ViewModel.IndividualAssessmentSheetCategories.AddNewVMToList();
            ViewModel.IndividualAssessmentSheetCategories.VMList.Sort(AssessmentSheetCategoryVM.Compare);
        }

        private void button_editIndAsc_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.IndividualAssessmentSheetCategories.EditVM.Values = ViewModel.IndividualAssessmentSheetCategories.PossibleValues.Where(i => i.IsEditSelected).ToList();
            ViewModel.IndividualAssessmentSheetCategories.PossibleValues.ForEach(i => i.IsEditSelected = false);

            popup_values.IsOpen = false;
        }

        private void Popupedit_environmentPersonSearch_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ViewModel.EnvironmentPersons.NewVM.Person == null || !BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.PersonView_View))
            {
                return;
            }

            CreateModalViewWindow(ViewModel.EnvironmentPersons.NewVM.Person);
        }

        private void Popupedit_environmentOrganisationSearch_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ViewModel.EnvironmentOrganisations.NewVM.Organisation == null || !BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.OrganisationView_View))
            {
                return;
            }

            CreateModalViewWindow(ViewModel.EnvironmentOrganisations.NewVM.Organisation);
        }

        private void Popupedit_costBearer_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ViewModel.CostBearers.NewVM.CostBearer == null || !BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.OrganisationView_View))
            {
                return;
            }

            CreateModalViewWindow(ViewModel.CostBearers.NewVM.CostBearer, true);
        }

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

            CreateModalViewWindow(ViewModel.EmployeeRelations.NewVM.Employee);
        }

        private void TableView_OnRowDoubleClick(object sender, RowDoubleClickEventArgs e)
        {
            var tableView = (TableView)sender;
            object selectedVM = tableView.Grid.GetRow(e.HitInfo.RowHandle);

            if (selectedVM == null)
            {
                return;
            }

            var typeOfSelectedVM = selectedVM.GetType();

            if ((typeOfSelectedVM == typeof(CustomerCostBearerRealtionVM)) || (typeOfSelectedVM == typeof(CustomerOrganisationRelationVM)) && BeWoApp.LoggedOnUser.HasRight(UserRightType.OrganisationView_View))
            {
                var newOrganisation = typeOfSelectedVM == typeof (CustomerCostBearerRealtionVM)
                    ? ((CustomerCostBearerRealtionVM) selectedVM).CostBearer
                    : ((CustomerOrganisationRelationVM) selectedVM).Organisation;

                CreateModalViewWindow(newOrganisation, typeOfSelectedVM == typeof(CustomerCostBearerRealtionVM));
            }

            if (typeOfSelectedVM == typeof(CustomerPersonRelationVM) && BeWoApp.LoggedOnUser.HasRight(UserRightType.PersonView_View))
            {
                CreateModalViewWindow(((CustomerPersonRelationVM)selectedVM).Person);
            }

            if (typeOfSelectedVM == typeof(CustomerEmployeeRelationVM) && BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_View))
            {
                CreateModalViewWindow(((CustomerEmployeeRelationVM)selectedVM).Employee);
            }

            if (typeOfSelectedVM == typeof(CustomerTeamRelationVM) && BeWoApp.LoggedOnUser.HasRight(UserRightType.TeamView_ViewAll))
            {
                CreateModalViewWindow(((CustomerTeamRelationVM)selectedVM).Team);
            }
        }

        private void CreateModalViewWindow<T>(T pDC, bool isCostBearer = false) where T : IDataContract
        {
            var pDCType = pDC.GetType();

            if (pDCType == typeof(CompactEmployeeDC))
            {
                VMFactory.CreateEmployeeVMAsync((pDC as CompactEmployeeDC).EmployeeOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, CustomerView>(cb, this, () => this.Dispatch(
                            () => BeWoUtils.UpdateAllViews(ViewModel.EmployeeRelations.NewVM.Employee ?? (pDC as CompactEmployeeDC))))));
            }

            if (pDCType == typeof(CompactOrganisationDC))
            {
                VMFactory.CreateOrganisationVMAsync((pDC as CompactOrganisationDC).OrganisationOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<OrganisationVM, OrganisationDC, CustomerView>(cb, this, () => this.Dispatch(
                            delegate
                            {
                                CompactOrganisationDC selectedOrganisation = (isCostBearer ? ViewModel.CostBearers.NewVM.CostBearer : ViewModel.EnvironmentOrganisations.NewVM.Organisation) ?? (pDC as CompactOrganisationDC);
                                BeWoUtils.UpdateAllViews(selectedOrganisation);
                            }), (s, args) => this.Dispatch(delegate { }))));
            }

            if (pDCType == typeof(CompactPersonDC))
            {
                VMFactory.CreatePersonVMAsync((pDC as CompactPersonDC).PersonOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<PersonVM, PersonDC, CustomerView>(cb, this, () => this.Dispatch(
                            () => BeWoUtils.UpdateAllViews(ViewModel.EnvironmentPersons.NewVM.Person ?? (pDC as CompactPersonDC))), personSavedOrUpdated: (s, args) => this.Dispatch(delegate{}))));
            }

            if (pDCType == typeof(CompactTeamDC))
            {
                VMFactory.CreateTeamVMAsync((pDC as CompactTeamDC).TeamOid,
                    cb => this.Dispatch(
                        () => BeWoUtils.OpenModalViewWindow<TeamVM, TeamDC, CustomerView>(cb, this, () => this.Dispatch(
                            () => BeWoUtils.UpdateAllViews(ViewModel.TeamRelations.NewVM.Team ?? (pDC as CompactTeamDC))))));
            }
        }

        private void Popupedit_teamRelations_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ViewModel.TeamRelations.NewVM.Team == null || !BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit)sender, e) || !BeWoApp.LoggedOnUser.HasRight(UserRightType.TeamView_ViewAll))
                return;

            CreateModalViewWindow(ViewModel.TeamRelations.NewVM.Team);
        }

        private void EmailBtnClick(object sender, RoutedEventArgs e)
        {
            BeWoUtils.OpenMailClient(ViewModel.EMail);
        }

        private void btnShowHistory_Click(object sender, RoutedEventArgs e)
        {
            ShowHistory();
        }

        private void ShowHistory()
        {
            if (!ViewModel.IsNew)
            {
                double height = 450;

                var dlg = new CustomerHistoryDialog();

                dlg.Width = 800;

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

                dlg.Height = height;

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

                //ServiceFacade.DoOperationsServiceAsync(
                //	s => s.GetServiceRecordHistory(ViewModel.DataContract.CustomerOid.Value),
                //	r => this.Dispatch(
                //		delegate
                //		{
                //			dlg.CustomerHistoryView.InitView(r);
                //			dlg.ShowDialog();
                //		}));
            }
        }

        private void MedVerAusListeClick(object sender, RoutedEventArgs eventArgs)
        {
            var mvl = ViewModel.AktuelleMedikamentenverordnungsliste;

            var x = ServiceFacade.DoCustomerServiceSync(s => s.GetCompactCustomerDC(ViewModel.CommitToDataContract().CustomerOid.Value));
            OpenMedikamentenverordnungslistenEditView(new MedikamentenverordnungslisteVM(new MedikamentenverordnungslisteDC()) { Gueltig = true, Customer = x, Medikamentenverordnungen = new TrulyObservableCollection<MedikamentenverordnungDC>(mvl.Medikamentenverordnungen) });
        }

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

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

        private void NeueMVLHinzufuegenClick(object sender, RoutedEventArgs e)
        {
            var newvm = ViewModel.MedVerordnungslisten.NewVM;

            var currentCustomer = ServiceFacade.DoCustomerServiceSync(s => s.GetCompactCustomerDC(ViewModel.CommitToDataContract().CustomerOid.Value));
            newvm.Gueltig = true;
            newvm.Customer = currentCustomer;
            OpenMedikamentenverordnungslistenEditView(newvm);
        }

        private void OpenMedikamentenverordnungslistenEditView(MedikamentenverordnungslisteVM vm, bool isInEditMode = false)
        {
            var mvev = new MedikamentenverordnungslistenEditView(ViewModel.MedVerordnungslisten, vm, ViewModel.MedArten.ToList(), isInEditMode) { ParentView = this };

            popup_content.Child = mvev;

            double height = 600;
            double width = 1000;

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

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

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

                            ClosePopupView();
                        }));
                mvev.CommandBindings.Add(
                    new CommandBinding(ApplicationCommands.Save,
                        (s, e) =>
                        {
                            mvev.SaveData();
                            ClosePopupView();

                            ReloadViewModel();

                            grid_aktuellemvl.RefreshData();
                        }));
            }

            SetPopupViewVisible(true);
        }

        private void UpdateUris()
        {
            if (ViewModel.AktuelleMedikamentenverordnungsliste != null)
            {
                var url = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.AktuelleMedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.Medikamentenverordnungsliste)));
                LinkListeMitZusatzFeldern.NavigateUri = new Uri(url);
            }

            if (ViewModel.Bedarfsmedikamentenverordnungsliste != null)
            {
                var url2 = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.Bedarfsmedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.Medikamentenverordnungsliste)));
                LinkBedarfsListeMitZusatzFeldern.NavigateUri = new Uri(url2);
            }
        }

        private void LinkAktuelleListeDrucken_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            var url = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.AktuelleMedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.Medikamentenverordnungsliste)));
            LinkAktuelleListeDrucken.NavigateUri = new Uri(url);
            BeWoUtils.NavigateToReportUri(((Hyperlink)sender).NavigateUri.ToString(), "Aktuelle Medikamentenverordnungsliste");
        }

        private void LinkListeDrucken_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            BeWoUtils.NavigateToReportUri(((Hyperlink)sender).NavigateUri.ToString(), "Alte Medikamentenverordnungsliste");
        }

        private void LinkListeMitZusatzeldernDrucken_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            var url = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.AktuelleMedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.MedikamentenverordnungslisteMitZusatzfeldern)));
            LinkListeMitZusatzFeldern.NavigateUri = new Uri(url);
            BeWoUtils.NavigateToReportUri(((Hyperlink)sender).NavigateUri.ToString(), "Medikamentenverordnungsliste Mit Zusatzfeldern");
        }

        private void tabitem_medver_Selected(object sender, RoutedEventArgs e)
        {
            if (grid_Medikamentenverordnung == null)
            {
                grid_Medikamentenverordnung = root.Resources["grid_medikamentenverordnungshistorie"] as GridControl;
                GroupBoxMedikamentenverordnungen.Content = grid_Medikamentenverordnung;

                if (grid_Medikamentenverordnung != null)
                {
                    grid_Medikamentenverordnung.Columns[1].SortMode = ColumnSortMode.Custom;
                    grid_Medikamentenverordnung.SortBy(grid_Medikamentenverordnung.Columns[1]);
                }
            }

            if (grid_aktuellemvl == null)
            {
                grid_aktuellemvl = root.Resources["grid_aktuellemvl"] as GridControl;
                if (grid_aktuellemvl != null)
                    AktuelleMVRGrid.Children.Add(grid_aktuellemvl);

                if (grid_aktuellemvl != null)
                {
                    grid_aktuellemvl.Columns[1].SortMode = ColumnSortMode.Custom;
                    grid_aktuellemvl.SortBy(grid_aktuellemvl.Columns[1]);
                }
            }

            if (grid_bedarfsmvl == null)
            {
                grid_bedarfsmvl = root.Resources["grid_bedarfsmvl"] as GridControl;
                if (grid_bedarfsmvl != null)
                    BedarfsMVRGrid.Children.Add(grid_bedarfsmvl);
            }

            if (ViewModel.AktuelleMedikamentenverordnungsliste != null)
            {
                var url = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.AktuelleMedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.Medikamentenverordnungsliste)));
                LinkAktuelleListeDrucken.NavigateUri = new Uri(url);

                url = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.AktuelleMedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.MedikamentenverordnungslisteMitZusatzfeldern)));
                LinkListeMitZusatzFeldern.NavigateUri = new Uri(url);
            }

            if (ViewModel.Bedarfsmedikamentenverordnungsliste != null)
            {
                var url2 = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.Bedarfsmedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.Medikamentenverordnungsliste)));
                LinkBedarfsListeDrucken.NavigateUri = new Uri(url2);

                url2 = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.Bedarfsmedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.MedikamentenverordnungslisteMitZusatzfeldern)));
                LinkBedarfsListeMitZusatzFeldern.NavigateUri = new Uri(url2);
            }
        }

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

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

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

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

        private void RemoveMedVerordnungClick(object sender, RoutedEventArgs e)
        {
            if (ViewModel.AktuelleMedikamentenverordnungsliste == null)
                return;

            var listenOid = ViewModel.AktuelleMedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid;
            if (!listenOid.HasValue) return;

            var antwort = MessageBox.Show("Sind Sie sicher, dass Sie diese Medikamentenverordnungsliste löschen wollen?", "Löschen", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (antwort.Equals(MessageBoxResult.Cancel))
                return;

            ServiceFacade.DoCustomerServiceSync(a => a.DeleteMedikamentenverordnungsliste(listenOid.Value));
            ViewModel.Medikamentenverordnungslisten.Remove(ViewModel.AktuelleMedikamentenverordnungsliste.CommitToDataContract());
            ReloadViewModel();
            grid_aktuellemvl.RefreshData();
        }

        private void EditMedVerordnungClick(object sender, RoutedEventArgs e)
        {
            var mvl = ViewModel.AktuelleMedikamentenverordnungsliste;

            OpenMedikamentenverordnungslistenEditView(mvl, true);
        }

        private void RemoveHistMedVOClick(object sender, RoutedEventArgs e)
        {
            var cv = grid_Medikamentenverordnung.GetCurrentValue<MedikamentenverordnungslisteVM>().CommitToDataContract();
            var listenOid = cv.MedikamentenverordnungslistenOid;
            if (listenOid == null)
                return;

            var antwort = MessageBox.Show(string.Format("Sind Sie sicher, dass Sie die Medikamentenverordnungsliste vom {0} von {1} löschen wollen?", cv.ErstellDatum, cv.Ersteller), "Löschen", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (antwort.Equals(MessageBoxResult.Cancel))
                return;

            ServiceFacade.DoCustomerServiceSync(a => a.DeleteMedikamentenverordnungsliste(listenOid.Value));
            ViewModel.MedVerordnungslisten.VMList.Remove(grid_Medikamentenverordnung.GetCurrentValue<MedikamentenverordnungslisteVM>());

            ReloadViewModel();
            grid_Medikamentenverordnung.RefreshData();
        }

        // Scheduler
        //public NewSchedulerView NewSchedulerView;
        //private bool mWaitDialogShown;

        //private void tabitem_scheduler_Selected(object sender, RoutedEventArgs e)
        //{
        //	if (NewSchedulerView != null) return;

        //	NewSchedulerView = new NewSchedulerView(ViewModel.DataContract.CustomerOid.Value) {IsInCustomerViewMode = true};

        //	if (NewSchedulerView == null) return;

        //	TerminplanungsGrid.Children.Add(NewSchedulerView);
        //	var fadein2 = new DoubleAnimation(1, new Duration(TimeSpan.FromSeconds(1)));
        //	TerminplanungsGrid.BeginAnimation(OpacityProperty, fadein2);

        //	NewSchedulerView.ShowView();

        //	HideWaitDialog();
        //}

        //private void HideWaitDialog()
        //{
        //	if (!mWaitDialogShown) return;

        //	mWaitDialogShown = false;
        //	BeWoApp.MainControl.EndWaiting();
        //}

        //private void SelektierenBtn_OnClick(object sender, RoutedEventArgs e)
        //{
        //	if(NewSchedulerView != null && ViewModel.DataContract.CustomerOid.HasValue)
        //		NewSchedulerView.PreselectCustomer(ViewModel.DataContract.CustomerOid.Value);
        //}

        private void RemoveBedarfsMedVerordnungClick(object sender, RoutedEventArgs e)
        {
            if (ViewModel.Bedarfsmedikamentenverordnungsliste == null)
                return;

            var listenOid = ViewModel.Bedarfsmedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid;
            if (!listenOid.HasValue) return;

            var antwort = MessageBox.Show("Sind Sie sicher, dass Sie diese Medikamentenverordnungsliste löschen wollen?", "Löschen", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (antwort.Equals(MessageBoxResult.Cancel))
                return;

            ServiceFacade.DoCustomerServiceSync(a => a.DeleteMedikamentenverordnungsliste(listenOid.Value));
            ViewModel.Medikamentenverordnungslisten.Remove(ViewModel.AktuelleMedikamentenverordnungsliste.CommitToDataContract());
            ReloadViewModel();
            grid_bedarfsmvl.RefreshData();
        }

        private void EditBedarfMedVerordnungClick(object sender, RoutedEventArgs e)
        {
            var bvl = ViewModel.Bedarfsmedikamentenverordnungsliste;

            OpenMedikamentenverordnungslistenEditView(bvl, true);
        }

        private void MedVerAusBedarfsListeClick(object sender, RoutedEventArgs e)
        {
            var bml = ViewModel.Bedarfsmedikamentenverordnungsliste;

            var x = ServiceFacade.DoCustomerServiceSync(s => s.GetCompactCustomerDC(ViewModel.CommitToDataContract().CustomerOid.Value));
            OpenMedikamentenverordnungslistenEditView(new MedikamentenverordnungslisteVM(new MedikamentenverordnungslisteDC()) { Gueltig = true, MedListType = true, Customer = x, Medikamentenverordnungen = new TrulyObservableCollection<MedikamentenverordnungDC>(bml.Medikamentenverordnungen) });
        }

        private void LinkBedarfsListeDrucken_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            var url = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.Bedarfsmedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.Medikamentenverordnungsliste)));
            LinkBedarfsListeDrucken.NavigateUri = new Uri(url);
            BeWoUtils.NavigateToReportUri(((Hyperlink)sender).NavigateUri.ToString(), "Aktuelle Medikamentenverordnungsliste");
        }

        private void LinkBedarfsListeMitZusatzeldernDrucken_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            var url = BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, ViewModel.Bedarfsmedikamentenverordnungsliste.CommitToDataContract().MedikamentenverordnungslistenOid, Utils.EnumName(ReportTypes.MedikamentenverordnungslisteMitZusatzfeldern)));
            LinkBedarfsListeMitZusatzFeldern.NavigateUri = new Uri(url);
            BeWoUtils.NavigateToReportUri(((Hyperlink)sender).NavigateUri.ToString(), "Bedarfsmedikamentenverordnungsliste Mit Zusatzfeldern");
        }

        private void MVHistoryEntryHyperlinkClick(object sender, RoutedEventArgs e)
        {
            var hl = (Hyperlink)sender;
            var tb = (TextBlock)hl.Parent;
            var ce = (CellEditor)tb.TemplatedParent;
            var r = (MedikamentenverordnungslisteVM)ce.RowData.Row;
            var url = string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, r.DataContract.MedikamentenverordnungslistenOid.Value, Utils.EnumName(ReportTypes.HistorischeMedikamentenverordnungsliste));
            BeWoUtils.NavigateToReportUri(url, "Alte Medikamentenverordnungsliste");
        }

        private void Grid_medikamentenverordnungshistorie_OnCustomColumnSort(object sender, CustomColumnSortEventArgs e)
        {
            var v1String = e.Value1.ToString();
            var v2String = e.Value2.ToString();
            var dt1 = Convert.ToDateTime(v1String.Substring(v1String.Length - 10, 10));
            var dt2 = Convert.ToDateTime(v2String.Substring(v2String.Length - 10, 10));

            e.Result = Comparer<DateTime>.Default.Compare(dt1, dt2) * -1;
            e.Handled = true;
        }

        private void Grid_aktuellemedikamentenverordnungsliste_OnCustomColumnSort(object sender, CustomColumnSortEventArgs e)
        {
            var comparer = new MedVerDetailOrderClass();

            e.Result = comparer.Compare(e.Value1.ToString(), e.Value2.ToString());
            e.Handled = true;
        }

        private void button_bargeldtransaktionDeleteClick(object sender, RoutedEventArgs e)
        {
            //var transaktion = grid_bargeldtransaktionen.GetCurrentValue<BargeldtransaktionsVM>();
            //ViewModel.Bargeldtransaktionsliste.VMList.Remove(transaktion);

            //var tmp = 0m;

            //foreach (var tvm in ViewModel.Bargeldtransaktionsliste.VMList.OrderBy(o => o.Zahlungsdatum))
            //{
            //    tvm.Transaktionskassenbestand = tmp + tvm.Betrag * (tvm.Zahlungstyp.Enum == Zahlungstyp.Auszahlung ? -1 : 1);
            //    tmp = tvm.Transaktionskassenbestand != null ? tvm.Transaktionskassenbestand.Value : 0m;
            //}

            //grid_bargeldtransaktionen.RefreshData();
        }

        private void AddBargeldTransaktion(object sender, RoutedEventArgs e)
        {
            //if (!ValidationTrigger.Validate(NeueTransaktionsGrid))
            //{
            //    return;
            //}

            //ViewModel.Bargeldtransaktionsliste.NewVM.Customer = ServiceFacade.DoCustomerServiceSync(s => s.GetCompactCustomerDC(ViewModel.CommitToDataContract().CustomerOid.Value));
            //var neueTransaktion = ViewModel.Bargeldtransaktionsliste.NewVM;

            //var transaktionsBetrag = neueTransaktion.Betrag * (neueTransaktion.Zahlungstyp.Enum == Zahlungstyp.Auszahlung ? -1 : 1);

            //var groesstesTransaktionsdatum = new DateTime(1, 1, 1);
            //foreach (var tVM in ViewModel.Bargeldtransaktionsliste.VMList)
            //{
            //    if (tVM.Zahlungsdatum > groesstesTransaktionsdatum && tVM.Zahlungsdatum != null)
            //        groesstesTransaktionsdatum = tVM.Zahlungsdatum.Value.GetShortDateTime();
            //}

            //if (neueTransaktion.Zahlungsdatum <= groesstesTransaktionsdatum)
            //{
            //    var vorherigeTransaktion = ViewModel.Bargeldtransaktionsliste.VMList.OrderByDescending(o => o.Zahlungsdatum).FirstOrDefault(f => f.Zahlungsdatum <= neueTransaktion.Zahlungsdatum);
            //    var liste = vorherigeTransaktion == null ?
            //        ViewModel.Bargeldtransaktionsliste.VMList.OrderBy(o => o.Zahlungsdatum) :
            //        ViewModel.Bargeldtransaktionsliste.VMList.Where(w => w.Zahlungsdatum > vorherigeTransaktion.Zahlungsdatum).OrderBy(o => o.Zahlungsdatum);

            //    neueTransaktion.Transaktionskassenbestand = (vorherigeTransaktion == null ? 0m : vorherigeTransaktion.Transaktionskassenbestand) + transaktionsBetrag;

            //    var tmp = neueTransaktion.Transaktionskassenbestand;

            //    foreach (var tvm in liste)
            //    {
            //        tvm.Transaktionskassenbestand = tmp + tvm.Betrag * (tvm.Zahlungstyp.Enum == Zahlungstyp.Auszahlung ? -1 : 1);
            //        tmp = tvm.Transaktionskassenbestand != null ? tvm.Transaktionskassenbestand.Value : 0m;
            //    }
            //}
            //else
            //{
            //    neueTransaktion.Transaktionskassenbestand = ViewModel.Kassenbestand + transaktionsBetrag;
            //}

            //ViewModel.Bargeldtransaktionsliste.AddNewVMToList();

            //grid_bargeldtransaktionen.RefreshData();
        }

        private void LinkZahlungsbelegDruckenClick(object sender, RoutedEventArgs e)
        {
            //var transaktion = grid_bargeldtransaktionen.GetCurrentValue<BargeldtransaktionsVM>().CommitToDataContract();

            //BeWoUtils.ShowReport("Zahlungsbeleg", null, new Dictionary<String, Object> { { "transaktion", transaktion } }, ReportEnum.ZahlungsbelegEnum);
        }

        private void UIElement_OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //var zeitraum = new DateTime(Convert.ToInt32(KassenbuchJahresCB.SelectedItem), KassenbuchMonatsCB.SelectedIndex + 1, 1);

            //var selektierteTransaktionen = ViewModel.Bargeldtransaktionsliste.CopyToDCList(true).Where(w => w.Zahlungsdatum != null && w.Zahlungsdatum.Value.Year == zeitraum.Year && w.Zahlungsdatum.Value.Month == zeitraum.Month).ToList();

            //if (selektierteTransaktionen.Count == 0)
            //{
            //    MessageBox.Show("In dem gewählten Zeitraum gibt es weder Ein- noch Auszahlungen. Bitte wählen Sie einen anderen Zeitraum", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
            //    return;
            //}

            //var variablenDiktionaer = new Dictionary<String, Object>{
            //    { "zeitraum", zeitraum },
            //    { "transaktionen",  selektierteTransaktionen}
            //};

            //BeWoUtils.ShowReport("Kassenbuch von " + ViewModel.FirstName + " " + ViewModel.LastName, null, variablenDiktionaer, ReportEnum.KassenbuchReportEnum);
        }

        private void Grid_Bargeldtransaktionen_OnCustomColumnSort(object sender, CustomColumnSortEventArgs e)
        {
            e.Result = DateTime.Compare(Convert.ToDateTime(e.Value1), Convert.ToDateTime(e.Value2));
            e.Handled = true;
        }

        // TODO: wie Dokumente umbauen
        private void Tabitem_Bargeldverwaltung_OnSelected(object sender, RoutedEventArgs e)
        {
			
            if (ViewModel.IsNew)
            {
                MessageBox.Show("Bevor Sie Bargeldkassen anlegen können, muss dieser Datensatz zuerst gespeichert werden.", "Erst speichern bitte", MessageBoxButton.OK, MessageBoxImage.Information);
				return;
                //BargeldverwaltungsGrid.Visibility = Visibility.Collapsed;
            }
            //else
            //{
            //    grid_bargeldtransaktionen.Columns[1].SortMode = ColumnSortMode.Custom;
            //    grid_bargeldtransaktionen.SortBy(grid_bargeldtransaktionen.Columns[1]);
            //}

            if (tabitem_Bargeldverwaltung.Content == null)
            {
                var view = new BargeldkassenView(TableID.Customer, ViewModel.DataContract.CustomerOid.Value);

                tabitem_Bargeldverwaltung.Content = view;
            }
        }

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

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

        private void GdBComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ViewModel.GradDerBehinderung = GdBComboBox.SelectedValue.ToString();
        }

    }

    public class MVListConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return new Uri(BeWoWpfUtils.GetHTMLEncodedURL(string.Format("{0}/ReportView.aspx?mvlOid={1}&type={2}", BeWoApp.SiteOfOrigin, System.Convert.ToInt64(value), Utils.EnumName(ReportTypes.HistorischeMedikamentenverordnungsliste))));
        }

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

    public class MedVerDetailOrderClass : IComparer<String>
    {
        public int Compare(String x, String y)
        {
            if (x.Equals(y))
                return 0;

            switch (y)
            {
                case "PSY":
                    return 1;
                case "BPS":
                    return x.Equals("PSY") ? -1 : 1;
                case "DPS":
                    return x.Equals("PSY") ||
                           x.Equals("BPS") ? -1 : 1;
                case "SOM":
                    return x.Equals("PSY") ||
                           x.Equals("BPS") ||
                           x.Equals("DPS") ? -1 : 1;
                case "BSO":
                    return x.Equals("PSY") ||
                           x.Equals("BPS") ||
                           x.Equals("DPS") ||
                           x.Equals("SOM") ? -1 : 1;
                case "DSO":
                    return -1;
                default:
                    return 0;
            }
        }
    }

}
