using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;

using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.View.Controls;
using BeWo.ViewModel;
using BeWo.ViewModel.ListViewModel;

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

using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Docking;

namespace BeWo.View.Detail
{
    public partial class AssessmentSheetEntryView : BeWoView
    {
        private string _EditCol;

        private AssessmentSheetRow _EditRow;

        private CompactCustomerDC _SelectedCustomerDC;

        private AssessmentSheetEntryListVM _ViewModel;

        private bool mSaveAllowed;

        private List<AssessmentSheetCategoryDC> _Categories;

        internal bool _PreventReloadViewModel;

        private bool _IgnoreDayComboChange;

        private bool _ShowMonthView;

		private List<AdditionalServiceDC> _AdditionalServices;

        public AssessmentSheetEntryView()
        {
            this.InitializeComponent();

            this.InitDateCombos();

            this.mSaveAllowed = BeWoApp.LoggedOnUser.HasRight(UserRightType.AssessmentSheet_Edit) && BeWoApp.LoggedOnUser.HasRight(UserRightType.AssessmentSheet_Delete);

			_AdditionalServices = ServiceFacade.DoOperationsServiceSync(o => o.GetAllAdditionalService());

            ShowWeek();
        }

        public AssessmentSheetEntryListVM ViewModel
        {
            get { return _ViewModel; }
            set
            {
                _ViewModel = value;
                _ViewModel.ServiceRecords = _ServiceRecords;
                grid.DataContext = value;
            }
        }

        private List<ServiceRecordVM> _ServiceRecords;

        public List<ServiceRecordVM> ServiceRecords
        {
            get { return _ServiceRecords; }
            set
            {
                if (_ViewModel != null)
                    _ViewModel.ServiceRecords = value;
                _ServiceRecords = value;

                var template = gridView.ColumnHeaderTemplate;
                gridView.ColumnHeaderTemplate = null;
                gridView.ColumnHeaderTemplate = template;
            }
        }

        public override bool IsDirty
        {
            get
            {
                return this._ViewModel != null ? this._ViewModel.IsDirty : false;
            }
        }

        protected override void Save()
        {
            this.SaveChanges();
        }

        public void SetCustomer(CompactCustomerDC compactCustomerDC, List<AssessmentSheetCategoryDC> categories)
        {
            if (compactCustomerDC == null || categories == null)
                return;

            MessageBoxResult result = MessageBoxResult.No;
            //if (this.IsDirty)
            //{
            //    result = MessageBox.Show("Wollen Sie die Änderungen speichern?", "Änderungen speichern", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
            //}

            //if (result == MessageBoxResult.Yes)
            //{
            //    this._SelectedCustomerDC = c;

            //    this.Save();
            //}
            //else if (result == MessageBoxResult.No)
            //{
            //    this._SelectedCustomerDC = c;
            this._SelectedCustomerDC = compactCustomerDC;
            _Categories = categories;
                this.ReloadViewModel();
            //}
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.popup_valuepicker.IsOpen = false;
            this._EditRow.SetPropertyValue(this._EditCol, ((Grid)sender).Tag);
        }

        private void Header_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (this._SelectedCustomerDC != null)
            {
                GridColumnHeader header = sender as GridColumnHeader;
                GridColumn column = GridColumnHeader.GetGridColumn(header) as GridColumn;
                if (column != null && column.Name.StartsWith("colDay"))
                {
                    int day = int.Parse(column.Name.Replace("colDay", string.Empty));

                    var list = this._ViewModel.ServiceRecords.Where(i => i.Date.Value.Day.Equals(day)).ToList();

                    ServiceRecordPopUp popUp = new ServiceRecordPopUp(list);
                    BeWoApp.MainControl.ShowControlAsModalPopUp(popUp);
                }
            }
        }

        private void InitDateCombos()
        {
            this.comboMonth.ItemsSource = DateTimeFormatInfo.CurrentInfo.MonthNames.Where(s => !string.IsNullOrEmpty(s));
            
            var years = new List<int>();
            for (int i = 0; i <= 10; i++)
            {
                years.Add(DateTime.Now.Year - i);
            }

            this.comboYear.ItemsSource = years;
            

            SetSelectedDate(DateTime.Now);

            this.comboDay.SelectionChanged += this.comboDay_SelectionChanged;
            this.comboMonth.SelectionChanged += comboMonth_SelectionChanged;
            this.comboYear.SelectionChanged += comboYear_SelectionChanged;
        }
        
        private void ReloadViewModel()
        {
            if (!_PreventReloadViewModel)
            {
                if (_SelectedCustomerDC != null)
                {
	                IList<AdditionalServiceBookingDC> bookings = null;

                    DateTime dt = GetSelectedDate();
                    DateTime dtStart;
                    DateTime dtEnd;

                    if (_ShowMonthView)
                    {
                        UpdateMonthColumns();
                        dt = new DateTime(dt.Year, dt.Month, 1);
                        dtStart = dt;
                        dtEnd = dtStart.AddMonths(1);
                    } 
                    else
                    {
                        dt = GetFirstMondayOfWeek(dt);

                        dtStart = dt.Date;
                        dtEnd = dt.Date.AddDays(7);
                    }
                    
                    ServiceFacade.DoEmployeeServiceAsync(
                        s =>
                        s.GetAssessmentSheetEntriesForCustomer(_SelectedCustomerDC.Oid.Value, dtStart, dtEnd),
                        entries =>
                        this.Dispatch(
                            delegate
                                {
                                    ViewModel = new AssessmentSheetEntryListVM(entries, _Categories, dtStart);

									grid.ItemsSource = new BindingList<AssessmentSheetRow>(
														_Categories.Select(
															c =>
															{
																var row = new AssessmentSheetRow(_ViewModel, c, _SelectedCustomerDC.CustomerOid, dt, !_ShowMonthView);


																if (_AdditionalServices != null && _AdditionalServices.Any(additionalService => additionalService.Name.Equals(row.CategoryString)))
																{
																	if (bookings == null)
																		bookings = ServiceFacade.DoOperationsServiceSync(op => op.GetAllAdditionalServiceBookingsForCustomer(_SelectedCustomerDC.CustomerOid, dtStart, dtEnd));

																	int currentRowDay = 1;
																	for (DateTime iteratingDate = dtStart; iteratingDate < dtEnd; iteratingDate = iteratingDate.AddDays(1), currentRowDay++)
																	{
																		var summe = bookings.Count(b =>
																								   b.Date.Value.Day.Equals(iteratingDate.Day) &&
																								   b.Date.Value.Month.Equals(iteratingDate.Month) &&
																								   b.Date.Value.Year.Equals(iteratingDate.Year) &&
																								   b.AdditionalServiceRegion.AdditionalService.Name.Equals(row.CategoryString));

																		if (summe <= 0) continue;

																		AssessmentSheetValueVM newDay;
																		#region Switch
																		switch (currentRowDay)
																		{
																			case 1:
																				if (row.Day1 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day1.DataContract) { Sign = summe.ToString() };
																					row.Day1 = newDay;
																				}
																				break;
																			case 2:
																				if (row.Day2 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day2.DataContract) { Sign = summe.ToString() };
																					row.Day2 = newDay;
																				}
																				break;
																			case 3:
																				if (row.Day3 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day3.DataContract) { Sign = summe.ToString() };
																					row.Day3 = newDay;
																				}
																				break;
																			case 4:
																				if (row.Day4 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day4.DataContract) { Sign = summe.ToString() };
																					row.Day4 = newDay;
																				}
																				break;
																			case 5:
																				if (row.Day5 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day5.DataContract) { Sign = summe.ToString() };
																					row.Day5 = newDay;
																				}
																				break;
																			case 6:
																				if (row.Day6 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day6.DataContract) { Sign = summe.ToString() };
																					row.Day6 = newDay;
																				}
																				break;
																			case 7:
																				if (row.Day7 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day7.DataContract) { Sign = summe.ToString() };
																					row.Day7 = newDay;
																				}
																				break;
																			case 8:
																				if (row.Day8 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day8.DataContract) { Sign = summe.ToString() };
																					row.Day8 = newDay;
																				}
																				break;
																			case 9:
																				if (row.Day9 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day9.DataContract) { Sign = summe.ToString() };
																					row.Day9 = newDay;
																				}
																				break;
																			case 10:
																				if (row.Day10 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day10.DataContract) { Sign = summe.ToString() };
																					row.Day10 = newDay;
																				}
																				break;
																			case 11:
																				if (row.Day11 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day11.DataContract) { Sign = summe.ToString() };
																					row.Day11 = newDay;
																				}
																				break;
																			case 12:
																				if (row.Day12 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day12.DataContract) { Sign = summe.ToString() };
																					row.Day12 = newDay;
																				}
																				break;
																			case 13:
																				if (row.Day13 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day13.DataContract) { Sign = summe.ToString() };
																					row.Day13 = newDay;
																				}
																				break;
																			case 14:
																				if (row.Day14 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day14.DataContract) { Sign = summe.ToString() };
																					row.Day14 = newDay;
																				}
																				break;
																			case 15:
																				if (row.Day15 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day15.DataContract) { Sign = summe.ToString() };
																					row.Day15 = newDay;
																				}
																				break;
																			case 16:
																				if (row.Day16 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day16.DataContract) { Sign = summe.ToString() };
																					row.Day16 = newDay;
																				}
																				break;
																			case 17:
																				if (row.Day17 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day17.DataContract) { Sign = summe.ToString() };
																					row.Day17 = newDay;
																				}
																				break;
																			case 18:
																				if (row.Day18 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day18.DataContract) { Sign = summe.ToString() };
																					row.Day18 = newDay;
																				}
																				break;
																			case 19:
																				if (row.Day19 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day19.DataContract) { Sign = summe.ToString() };
																					row.Day19 = newDay;
																				}
																				break;
																			case 20:
																				if (row.Day20 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day20.DataContract) { Sign = summe.ToString() };
																					row.Day20 = newDay;
																				}
																				break;
																			case 21:
																				if (row.Day21 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day21.DataContract) { Sign = summe.ToString() };
																					row.Day21 = newDay;
																				}
																				break;
																			case 22:
																				if (row.Day22 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day22.DataContract) { Sign = summe.ToString() };
																					row.Day22 = newDay;
																				}
																				break;
																			case 23:
																				if (row.Day23 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day23.DataContract) { Sign = summe.ToString() };
																					row.Day23 = newDay;
																				}
																				break;
																			case 24:
																				if (row.Day24 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day24.DataContract) { Sign = summe.ToString() };
																					row.Day24 = newDay;
																				}
																				break;
																			case 25:
																				if (row.Day25 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day25.DataContract) { Sign = summe.ToString() };
																					row.Day25 = newDay;
																				}
																				break;
																			case 26:
																				if (row.Day26 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day26.DataContract) { Sign = summe.ToString() };
																					row.Day26 = newDay;
																				}
																				break;
																			case 27:
																				if (row.Day27 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day27.DataContract) { Sign = summe.ToString() };
																					row.Day27 = newDay;
																				}
																				break;
																			case 28:
																				if (row.Day28 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day28.DataContract) { Sign = summe.ToString() };
																					row.Day28 = newDay;
																				}
																				break;
																			case 29:
																				if (row.Day29 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day29.DataContract) { Sign = summe.ToString() };
																					row.Day29 = newDay;
																				}
																				break;
																			case 30:
																				if (row.Day30 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day30.DataContract) { Sign = summe.ToString() };
																					row.Day30 = newDay;
																				}
																				break;
																			case 31:
																				if (row.Day31 != null)
																				{
																					newDay = new AssessmentSheetValueVM(row.Day31.DataContract) { Sign = summe.ToString() };
																					row.Day31 = newDay;
																				}
																				break;
																		}

																		#endregion
																	}
																}

																return row;

															}).ToList());
									gridView.BestFitColumn(colCategory);

									UpdatePrintUrl(_SelectedCustomerDC.Oid.Value, dtStart, dtEnd);

                                }), false);
                }
            }
        }
        
        private DateTime GetFirstMondayOfWeek(DateTime dt)
        {
            while (dt.DayOfWeek != DayOfWeek.Monday)
                dt = dt.AddDays(-1);
            return dt;
        }

        private DateTime GetSelectedDate()
        {
            int year = (int)this.comboYear.SelectedItem;
            int month = this.comboMonth.SelectedIndex + 1;
            if (month == 0)
                month = 1;
            int day = this.comboDay.SelectedIndex + 1;
            if (day == 0)
                day = 1;
            DateTime dt = new DateTime(year, month, 1);   
            try
            {
                dt = new DateTime(year, month, day);   
            }
            catch (Exception ex)
            {

                dt = new DateTime(year, month, 1);   
            }

            return dt;
        }

        private void SetSelectedDate(DateTime dt)
        {
            _PreventReloadViewModel = true;
            UpdateDayCombo(dt);

            this.comboDay.SelectedItem = dt.Day;
            this.comboMonth.SelectedIndex = dt.Month - 1;
            this.comboYear.SelectedItem = dt.Year;

            UpdateColumnHeader();
            _PreventReloadViewModel = false;
        }

        private void UpdateDayCombo(DateTime dt)
        {
            var selectedDay = this.comboDay.SelectedIndex;
            var days = DateTime.DaysInMonth(dt.Year, dt.Month);

            var dayNumbers = new List<int>();
            this.comboDay.SelectionChanged -= this.comboDay_SelectionChanged;

            for (int i = 1; i <= days; i++)
            {
                dayNumbers.Add(i);
            }

            this.comboDay.ItemsSource = dayNumbers;

            this.comboDay.SelectionChanged += this.comboDay_SelectionChanged;

            if (dayNumbers.Count > selectedDay)
            {
                this.comboDay.SelectedIndex = selectedDay;
            }
            else
            {
                this.comboDay.SelectedIndex = 0;
            }

        }

        private void UpdateColumnHeader()
        {
            foreach (var c in grid.Columns)
            {
                //if (c.Name.EndsWith(e.RemovedItems[0].ToString()))
                //{
                if (c.CellStyle != null)
                    c.CellStyle = null;
                //}
            }

            DateTime selectedDate = GetSelectedDate();
            DateTime firstDay = new DateTime(selectedDate.Year, selectedDate.Month, 1);
            if (!_ShowMonthView)
                firstDay = GetFirstMondayOfWeek(selectedDate);

            
            foreach (var c in grid.Columns)
            {
                if (!c.Header.Equals("Kategorie"))
                {
                    c.Header = String.Format("{0}.", firstDay.Day);
                    
                    if (firstDay == selectedDate)
                    {
                        c.CellStyle = (Style)this.grid.FindResource("highlightedCell");
                    }
                    firstDay = firstDay.AddDays(1);
                }
            }
        }

        private void SaveChanges()
        {
            var lToDos = new List<Action<IEmployeeService>>();

            if (this._ViewModel.AddedCount > 0)
            {
                lToDos.Add(s => s.InsertNewAssessmentSheetEntries(this._ViewModel.CommitAdded()));
            }

            if (this._ViewModel.ChangedCount > 0)
            {
                lToDos.Add(s => s.UpdateAssessmentSheetEntries(this._ViewModel.CommitChanged()));
            }

            if (this._ViewModel.RemovedCount > 0)
            {
                lToDos.Add(s => s.DeactivateAssessmentSheetEntries(this._ViewModel.GetRemoved()));
            }

            ServiceFacade.DoMultipleEmployeeServicesAsync(lToDos, 
                () => this.Dispatch(
                    ReloadViewModel), false);

        }

        public void NextWeek()
        {
            DateTime dt = GetSelectedDate();

            if (_ShowMonthView)
                dt = dt.AddMonths(1);
            else
                dt = dt.AddDays(7);

            SetSelectedDate(dt);

            ReloadViewModel();
        }

        public void LastWeek()
        {
            DateTime dt = GetSelectedDate();
            if (_ShowMonthView)
                dt = dt.AddMonths(-1);
            else
                dt = dt.AddDays(-7);
            

            SetSelectedDate(dt);

            ReloadViewModel();
        }

        void comboYear_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _IgnoreDayComboChange = true;
            UpdateDayCombo(GetSelectedDate());
            UpdateColumnHeader();
            ReloadViewModel();
            _IgnoreDayComboChange = false;
        }

        void comboMonth_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _IgnoreDayComboChange = true;
            UpdateDayCombo(GetSelectedDate());
            UpdateColumnHeader();
            ReloadViewModel();
            _IgnoreDayComboChange = false;
        }

        private void comboDay_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_IgnoreDayComboChange)
            {
                if (e.RemovedItems != null && e.RemovedItems.Count > 0)
                {
                    UpdateColumnHeader();

                    int day = (int) e.RemovedItems[0];

                    DateTime selectedDate = GetSelectedDate();
                    DateTime lastDate = new DateTime(selectedDate.Year, selectedDate.Month, day);
                    DateTime startDate = new DateTime(lastDate.Year, lastDate.Month, 1);

                    if (!_ShowMonthView)
                    {
                        startDate = GetFirstMondayOfWeek(lastDate);
                        if (selectedDate < startDate || selectedDate >= startDate.AddDays(7))
                        {
                            ReloadViewModel();
                        }
                    }
                    else
                    {
                        if (selectedDate < startDate || selectedDate >= startDate.AddMonths(1))
                        {
                            ReloadViewModel();
                        }
                    }

                }
            }
            //this.grid.Columns.First(c => c.Name.EndsWith(e.AddedItems[0].ToString())).CellStyle = (Style)this.grid.FindResource("highlightedCell");
        }

        //private void header_Initialized(object sender, EventArgs e)
        //{
        //    GridColumnHeader header = sender as GridColumnHeader;
        //    //header.AddHandler(MouseDownEvent, new MouseButtonEventHandler(this.Header_MouseDown), true);

            
        //    GridColumn column = GridColumnHeader.GetGridColumn(header) as GridColumn;
        //    if (column != null && column.Name.StartsWith("colDay"))
        //    {
        //        int day = int.Parse(column.Name.Replace("colDay", string.Empty));
        //        if (this._headers.ContainsKey(day))
        //        {
        //            this._headers.Remove(day);
        //        }

        //        this._headers.Add(day, header);
        //    }
        //}

        private void popup_valuepicker_Closed(object sender, EventArgs e)
        {
            if (IsDirty)
                Save();
            
        }

        private void AssessmentSheetValueControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        public void AssessmentSheetValueControl_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (BeWoApp.LoggedOnUser.HasRight(UserRightType.AssessmentSheet_Edit)
                && BeWoApp.LoggedOnUser.HasRight(UserRightType.AssessmentSheet_Delete))
            {
                _EditRow = grid.GetRow(grid.View.GetRowHandleByMouseEventArgs(e)) as AssessmentSheetRow;

                var shouldReturn = false;
                ServiceFacade.DoEmployeeServiceSync(lol => shouldReturn = lol.IsAssessmentSheetEntryBelongingToAS(_EditRow.CategoryOid.Value));
                if (shouldReturn)
                    return;

                _EditCol = grid.View.GetColumnByMouseEventArgs(e).FieldName;

                listbox_valuepicker.ItemsSource = _EditRow.PossibleValues;

                popup_valuepicker.IsOpen = true;
            }
        }

        private void ButtonLastWeek_Click(object sender, RoutedEventArgs e)
        {
            LastWeek();
        }

        private void ButtonNextWeek_Click(object sender, RoutedEventArgs e)
        {
            NextWeek();
        }

        private void ButtonShowMonth_Click(object sender, RoutedEventArgs e)
        {
            ShowMonth();
        }

        private void ButtonShowWeek_Click(object sender, RoutedEventArgs e)
        {
            ShowWeek();
        }

        private void ShowMonth()
        {
            _ShowMonthView = true;
            btnShowMonth.Visibility = Visibility.Collapsed;
            btnShowWeek.Visibility = Visibility.Visible;

            btnMoveLastWeek.ToolTip = "Vergangenen Monat anzeigen";
            btnMoveNextWeek.ToolTip = "Nächsten Monat anzeigen";

            MakeMonthColumnsVisible(true);

            UpdateColumnHeader();
            ReloadViewModel();
        }


        private void ShowWeek()
        {
            _ShowMonthView = false;
            btnShowMonth.Visibility = Visibility.Visible;
            btnShowWeek.Visibility = Visibility.Collapsed;

            btnMoveLastWeek.ToolTip = "Vergangene Woche anzeigen";
            btnMoveNextWeek.ToolTip = "Nächste Woche anzeigen";

            MakeMonthColumnsVisible(false);

            UpdateColumnHeader();
            ReloadViewModel();
        }

        private void MakeMonthColumnsVisible(bool visible)
        {
            int index = 0;
            foreach (var column in grid.Columns)
            {
                if (index > 7)
                {
                    column.Visible = visible;

                    if (visible)
                        column.VisibleIndex = index;
                }
                index++;
            }
        }

        private void UpdateMonthColumns()
        {
            DateTime dt = GetSelectedDate();

            var days = DateTime.DaysInMonth(dt.Year, dt.Month);

            colDay31.Visible = days > 30;
            colDay30.Visible = days > 29;
            colDay29.Visible = days > 28;

            if (colDay29.Visible)
            {
                colDay29.VisibleIndex = 29;
            }
            if (colDay30.Visible)
            {
                colDay30.VisibleIndex = 30;
            }
            if (colDay31.Visible)
            {
                colDay31.VisibleIndex = 31;
            }
        }


        private void ColumnHeaderButton_Click(object sender, RoutedEventArgs e)
        {
            if (_SelectedCustomerDC != null)
            {
                var btn = sender as Button;

                if (btn != null)
                {
                    var header = btn.Tag as GridColumnHeader;

                    if (header != null)
                    {
                        var column = header.DataContext as GridColumn;
                        if (column != null && column.Name.StartsWith("colDay"))
                        {
                            int day = int.Parse(column.HeaderCaption.ToString().Replace(".", string.Empty));

                            var dt = new DateTime(ViewModel.StartDate.Year, ViewModel.StartDate.Month, day);
                            if (dt < ViewModel.StartDate)
                                dt = dt.AddMonths(1);

                            List<ServiceRecordVM> list = ViewModel.GetServiceRecordsForDate(dt);
                            if (list != null)
                            {
                                var popUp = new ServiceRecordPopUp(list);

                                var panel = new LayoutPanel
                                    {
                                        ShowPinButton = false,
                                        AllowDock = false,
                                        AllowDrag = true,
                                        AllowDockToDocumentGroup = false,
                                        Caption = String.Format("Einträge vom {0:dd/MM/yyyy}", dt)
                                    };

                                var border = new Border {Background = new SolidColorBrush(Color.FromRgb(195, 203, 206))};

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

                                panel.Content = border;

                                grid.Children.Add(popUp);
                                double width = 600;
                                if (LayoutManager.ActualWidth < 600)
                                    width = LayoutManager.ActualWidth;
                                double height = LayoutManager.ActualHeight - 100;
                                if (height < 100)
                                    height = LayoutManager.ActualHeight;
                                var floatGroup = new FloatGroup
                                    {
                                        FloatSize = new Size(width, height),
                                        FloatLocation =
                                            new Point((LayoutManager.ActualWidth - width)/2,
                                                      (LayoutManager.ActualHeight - height)/2),
                                        AllowDock = false
                                    };

                                floatGroup.Items.Add(panel);
                                LayoutManager.FloatGroups.Add(floatGroup);
                                LayoutManager.BringToFront(panel);
                            }
                        }
                    }
                }
            }
        }

        private void UpdatePrintUrl(long customerOid, DateTime dtStart, DateTime dtEnd)
        {
            long eOid = BeWoApp.LoggedOnUser.Employee.EmployeeOid;

            string url = BeWoApp.SiteOfOrigin + "/ReportView.aspx" + "?eOid=" + eOid + "&cOid=" + customerOid + "&m=" + dtStart.Month + "&y=" + dtStart.Year + "&type=" + Utils.EnumName(ReportTypes.AssessmentSheetReport);

            url = BeWoWpfUtils.GetHTMLEncodedURL(url);

            linkPdfExport.NavigateUri = new Uri(url);
        }


        public DockLayoutManager LayoutManager { get; set; }

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