using DevExpress.Data;
using DevExpress.Utils;
using DevExpress.Web;
using DevExpress.Web.ASPxThemes;
using DevExpress.Web.Mvc;
using DevExpress.Web.Mvc.UI;
using GreenTree.Nachtragsmanagement.Core.Authentication;
using GreenTree.Nachtragsmanagement.Web.Models.Appendix;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mvc.Html;
using GreenTree.Nachtragsmanagement.Web.Models.Deviation;
using GreenTree.Nachtragsmanagement.Core;
using GreenTree.Nachtragsmanagement.Services.Configuration;

namespace GreenTree.Nachtragsmanagement.Web.Extensions
{
    public static class GridViewSettingsHelper
    {
        /// <summary>
        /// Current user context
        /// </summary>
        public static UserContext _userContext = Core.CommonHelper.UserContext();

        /// <summary>
        /// Global configuration service
        /// </summary>
        public static IConfigurationService _configurationService;

        /// <summary>
        /// Creates GridViewSettings for the site gridView
        /// </summary>
        /// <param name="html">Current HtmlHelper context.</param>
        public static GridViewSettings SiteGridViewSettings(this System.Web.Mvc.HtmlHelper html)
        {
            var s = new GridViewSettings();

            s.Name = "devGridViewSite";
            s.KeyFieldName = "Id";
            s.CallbackRouteValues = new { Controller = "Site", Action = "PartialSites" };
            s.Width = Unit.Percentage(99);
            s.Settings.ShowHeaderFilterButton = true;
            s.Settings.ShowFilterRow = true;
            s.Settings.ShowFilterRowMenu = false;
            s.Settings.ShowFooter = true;
            s.Settings.ShowGroupPanel = true;
            s.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
            s.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollableHeight =
                (html.ViewData["ScrollHeight"] == null || (int)html.ViewData["ScrollHeight"] == -1)
                ? 400
                : (int)html.ViewData["ScrollHeight"];
            s.SettingsExport.Landscape = true;
            s.SettingsExport.FileName = "Baustellenliste";
            s.SettingsPopup.CustomizationWindow.Width = new Unit(250, UnitType.Pixel);
            s.SettingsPopup.CustomizationWindow.Height = new Unit(350, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Width = new Unit(353, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Height = new Unit(360, UnitType.Pixel);
            s.SettingsBehavior.EnableCustomizationWindow = true;
            s.SettingsBehavior.AllowHeaderFilter = true;
            s.SettingsPager.AlwaysShowPager = true;
            s.SettingsResizing.ColumnResizeMode = ColumnResizeMode.Control;
            s.SettingsPager.Position = PagerPosition.Bottom;
            s.SettingsPager.PageSizeItemSettings.Visible = true;
            s.SettingsPager.FirstPageButton.Visible = true;
            s.SettingsPager.LastPageButton.Visible = true;
            s.SettingsPager.NumericButtonCount = 5;

            s.Toolbars.Add(t =>
            {
                if (_userContext.CurrentUser.HasFunction("Site-Sites-Edit"))
                {
                    t.Items.Add(i =>
                    {
                        i.Text = "Baustelle anlegen";
                        i.Name = "AddSite";
                        i.Image.IconID = IconID.ActionsAdd16x16;
                    });
                }
                var refreshItem = t.Items.Add(GridViewToolbarCommand.Refresh);
                refreshItem.Text = "Aktualisieren";
                var expandItem = t.Items.Add(GridViewToolbarCommand.FullExpand);
                expandItem.Text = "Alle aufklappen";
                var collapseItem = t.Items.Add(GridViewToolbarCommand.FullCollapse);
                collapseItem.Text = "Alle einklappen";
                var filterItem = t.Items.Add(GridViewToolbarCommand.ClearFilter);
                filterItem.Text = "Filter entfernen";
                t.Items.Add(i =>
                {
                    i.Text = "Spalten anzeigen / ausblenden";
                    i.Name = "ToggleColumnChooser";
                    i.Image.IconID = IconID.OtherViewgridlines16x16gray;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Drucken";
                    i.Name = "Print";
                    i.Image.IconID = IconID.PrintDefaultprinter16x16;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Zurücksetzen";
                    i.Name = "ResetSettings";
                    i.Image.IconID = IconID.ActionsReset16x16;
                    i.BeginGroup = true;
                });
            });

            if (_userContext.CurrentUser.HasFunction("Site-Sites-Edit") || _userContext.CurrentUser.HasFunction("Site-Sites-Delete"))
            {
                s.Columns.Add(column =>
                {
                    column.Caption = "#";
                    column.SetDataItemTemplateContent(c =>
                    {
                        if (_userContext.CurrentUser.HasFunction("Site-Sites-Edit"))
                            html.ViewContext.Writer.Write(
                                "<a href=\"#\" onclick=\"editSite(" + DataBinder.Eval(c.DataItem, "Id") + ")\">Bearbeiten</a>");

                        if (_userContext.CurrentUser.HasFunction("Site-Sites-Delete"))
                            html.ViewContext.Writer.Write(
                                "<br /><a href=\"#\" onclick=\"confirmDelete(" + DataBinder.Eval(c.DataItem, "Id") + ")\">Löschen</a>");
                    });
                    column.Caption = "#";
                    column.Settings.AllowDragDrop = DefaultBoolean.False;
                    column.Settings.AllowSort = DefaultBoolean.False;
                    column.Width = new Unit(100, UnitType.Pixel);
                });
            }
            s.Columns.Add(column =>
            {
                column.Caption = "Kostenstelle";
                column.FieldName = "CustomNumber";
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
                column.MinWidth = 120;
                column.Width = new Unit(130, UnitType.Pixel);
                column.Settings.SortMode = DevExpress.XtraGrid.ColumnSortMode.Custom;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Bauvorhaben";
                column.FieldName = "Description";
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
                column.MinWidth = 150;
                column.Width = new Unit(150, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Start";
                column.FieldName = "Start";
                column.PropertiesEdit.DisplayFormatString = "dd.MM.yyyy";
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.DateRangePicker;
                column.MinWidth = 90;
                column.Width = new Unit(90, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Ende";
                column.FieldName = "End";
                column.PropertiesEdit.DisplayFormatString = "dd.MM.yyyy";
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.DateRangePicker;
                column.MinWidth = 90;
                column.Width = new Unit(90, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Abgeschl.";
                column.FieldName = "Finished";
                column.MinWidth = 70;
                column.Width = new Unit(70, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Offene VA";
                column.FieldName = "DeviationDescription";
                column.MinWidth = 230;
                column.Width = new Unit(230, UnitType.Pixel);
                column.SetDataItemTemplateContent(c =>
                {
                    var id = Convert.ToInt32(DataBinder.Eval(c.DataItem, "Id"));

                    var deviationDescription = DataBinder.Eval(c.DataItem, "DeviationDescription");
                    var text = deviationDescription == null
                        ? String.Empty
                        : deviationDescription.ToString();
                    var isLongText = text.ToString().Length > 80;

                    if (isLongText)
                    {
                        html.ViewContext.Writer.Write(text.Substring(0, 80) + " ...");
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick='showDeviationDescription(" + id + ",this)'><br />Anzeigen</a>");
                    }
                    else
                        html.ViewContext.Writer.Write(text);
                });
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Ges. VA-Sum.";
                column.FieldName = "DeviationValue";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 120;
                column.Width = new Unit(120, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Off. VA-Sum.";
                column.FieldName = "SiteDeviationValue";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 120;
                column.Width = new Unit(120, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Nachträge";
                column.FieldName = "AppendixDescription";
                column.MinWidth = 130;
                column.Width = new Unit(130, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Off. NT-Sum.";
                column.FieldName = "AppendixValueRemaining";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 120;
                column.Width = new Unit(120, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Verh. NT-Sum.";
                column.FieldName = "AppendixValueNegotiated";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 120;
                column.Width = new Unit(120, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Mitarbeiter";
                column.FieldName = "UserDescription";
                column.MinWidth = 245;
                column.Width = new Unit(245, UnitType.Pixel);
                column.SetDataItemTemplateContent(c =>
                {
                    var userDescriptions = DataBinder.Eval(c.DataItem, "UserDescriptions") as List<string>;

                    if (userDescriptions != null)
                    {
                        foreach (var description in userDescriptions)
                        {
                            var split = description.Split('|');

                            if (split.Length > 1)
                                html.ViewContext.Writer.Write(
                                    "<span style=\"float: left\">" + split[0] + "</span>" +
                                    "<span style=\"float: right\">" + split[1] + "</span><br />");
                            else
                                html.ViewContext.Writer.Write(
                                    "<span>" + split[0] + "</span><br />");
                        }

                    }
                });
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Kommentar";
                column.FieldName = "Comment";
                column.CellStyle.Wrap = DefaultBoolean.True;
                column.SetDataItemTemplateContent(c =>
                {
                    var id = Convert.ToInt32(DataBinder.Eval(c.DataItem, "Id"));

                    var comment = DataBinder.Eval(c.DataItem, "Comment");
                    var text = comment == null
                        ? String.Empty
                        : comment.ToString();
                    var isLongText = text.ToString().Length > 40;

                    if (isLongText)
                    {
                        html.ViewContext.Writer.Write(text.Substring(0, 40) + " ...");
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick='showComment(\"site\"," + id + ",this)'><br />Anzeigen</a>");
                    }
                    else
                        html.ViewContext.Writer.Write(text);

                    if (_userContext.CurrentUser.HasFunction("Site-Sites-Edit-Comment"))
                        html.ViewContext.Writer.Write(
                            (isLongText ? "&nbsp;" : "<br/>") +
                            "<a href=\"#\" onclick='editComment(\"site\"," + id + ",function() { devGridViewSite.PerformCallback(); })'>Bearbeiten</a>");
                });
                column.MinWidth = 120;
                column.Width = new Unit(120, UnitType.Pixel);
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Count,
                FieldName = "Description",
                DisplayFormat = "Anzahl<br/><i>{0:n0}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Count,
                FieldName = "Description",
                DisplayFormat = "Anzahl = {0:n0}"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "DeviationValue",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "VA ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "DeviationValue",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "VA ∑ = <i>{0:c2}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "SiteDeviationValue",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Off.VA ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "SiteDeviationValue",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Off.VA ∑ = <i>{0:c2}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "AppendixValueRemaining",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Off.NT ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "AppendixValueRemaining",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Off.NT ∑ = <i>{0:c2}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "AppendixValueNegotiated",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Verh.NT ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "AppendixValueNegotiated",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Verh.NT ∑ = <i>{0:c2}</i>"
            });

            s.ClientLayout = (sender, e) =>
            {
                if (e.LayoutMode == ClientLayoutMode.Loading)
                {
                    if (System.Web.HttpContext.Current.Session["SiteGridState"] != null)
                        e.LayoutData = (string)System.Web.HttpContext.Current.Session["SiteGridState"];
                    else
                    {
                        var userConfigItem = _configurationService.GetUserConfigItemByNameAndUserId("SiteGridLayoutState",
                            _userContext.CurrentUser.Id);

                        if (userConfigItem != null)
                        {
                            System.Web.HttpContext.Current.Session["SiteGridState"] = userConfigItem.Value;

                            e.LayoutData = (string)System.Web.HttpContext.Current.Session["SiteGridState"];
                        }
                        else
                            ((MVCxGridView)sender).SortBy(((MVCxGridView)sender).Columns[0], ColumnSortOrder.Ascending);
                    }
                }
                else
                {
                    System.Web.HttpContext.Current.Session["SiteGridState"] = e.LayoutData;

                    _configurationService.InsertOrUpdateUserConfigItem(new Core.Domain.Config.UserConfigItem
                    {
                        UserId = _userContext.CurrentUser.Id,
                        Name = "SiteGridLayoutState",
                        Value = e.LayoutData
                    });
                }
            };

            s.PreRender = s.BeforeGetCallbackResult = (sender, e) => {
                MVCxGridView gridView = sender as MVCxGridView;
                System.Web.HttpContext.Current.Session["SiteGridViewState"] = new MVCxGridViewState(gridView);
            };

            s.CustomColumnSort = (sender, e) =>
            {
                if (e.Column.FieldName != "CustomNumber") return;

                int.TryParse(e.GetRow1Value("CustomNumber").ToString(), out int rowVal1);
                int.TryParse(e.GetRow2Value("CustomNumber").ToString(), out int rowVal2);

                e.Result = (rowVal1).CompareTo(rowVal2);

                e.Handled = true;
            };

            s.ClientSideEvents.BeginCallback = "function (s, e) { e.customArgs['scrollHeight'] = [ gridScrollHeight ]; }";
            s.ClientSideEvents.ToolbarItemClick = "function (s, e) { onToolbarItemClick(s, e); }";

            s.Styles.AlternatingRow.BackColor = System.Drawing.Color.FromArgb(247, 247, 247);

            s.Styles.Footer.CssClass += "devExGridFooterPanel";
            s.Styles.GroupRow.CssClass += "devExGridGroupRow";

            return s;
        }

        /// <summary>
        /// Creates GridViewSettings for the deviation gridView
        /// </summary>
        /// <param name="html">Current HtmlHelper context.</param>
        public static GridViewSettings DeviationGridViewSettings(this System.Web.Mvc.HtmlHelper html)
        {
            var s = new GridViewSettings();

            s.Name = "devGridViewDeviation";
            s.KeyFieldName = "Id";
            s.CallbackRouteValues = new { Controller = "Deviation", Action = "PartialDeviations" };
            s.Width = Unit.Percentage(99);
            s.Settings.ShowHeaderFilterButton = true;
            s.Settings.ShowFilterRow = true;
            s.Settings.ShowFilterRowMenu = true;
            s.Settings.ShowFooter = true;
            s.Settings.ShowGroupPanel = true;
            s.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
            s.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollableHeight =
                (html.ViewData["ScrollHeight"] == null || (int)html.ViewData["ScrollHeight"] == -1)
                ? 400
                : (int)html.ViewData["ScrollHeight"];
            s.SettingsExport.Landscape = true;
            s.SettingsExport.FileName = "Vertragsabweichungsliste";
            s.SettingsPopup.CustomizationWindow.Width = new Unit(250, UnitType.Pixel);
            s.SettingsPopup.CustomizationWindow.Height = new Unit(350, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Width = new Unit(353, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Height = new Unit(360, UnitType.Pixel);
            s.SettingsBehavior.EnableCustomizationWindow = true;
            s.SettingsBehavior.AllowHeaderFilter = true;
            s.SettingsPager.AlwaysShowPager = true;
            s.SettingsResizing.ColumnResizeMode = ColumnResizeMode.Control;
            s.SettingsPager.Position = PagerPosition.Bottom;
            s.SettingsPager.PageSizeItemSettings.Visible = true;
            s.SettingsPager.FirstPageButton.Visible = true;
            s.SettingsPager.LastPageButton.Visible = true;
            s.SettingsPager.NumericButtonCount = 5;

            s.Toolbars.Add(t =>
            {
                var refreshItem = t.Items.Add(GridViewToolbarCommand.Refresh);
                refreshItem.Text = "Aktualisieren";
                var expandItem = t.Items.Add(GridViewToolbarCommand.FullExpand);
                expandItem.Text = "Alle aufklappen";
                var collapseItem = t.Items.Add(GridViewToolbarCommand.FullCollapse);
                collapseItem.Text = "Alle einklappen";
                var filterItem = t.Items.Add(GridViewToolbarCommand.ClearFilter);
                filterItem.Text = "Filter entfernen";
                t.Items.Add(i =>
                {
                    i.Text = "Spalten anzeigen / ausblenden";
                    i.Name = "ToggleColumnChooser";
                    i.Image.IconID = IconID.OtherViewgridlines16x16gray;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Drucken";
                    i.Name = "Print";
                    i.Image.IconID = IconID.PrintDefaultprinter16x16;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Zurücksetzen";
                    i.Name = "ResetSettings";
                    i.Image.IconID = IconID.ActionsReset16x16;
                    i.BeginGroup = true;
                });
            });

            s.Columns.Add(column =>
            {
                column.Caption = "#";
                column.FieldName = "CustomNumber";
                column.MinWidth = 50;
                column.Width = new Unit(60, UnitType.Pixel);
                column.Settings.AutoFilterCondition = AutoFilterCondition.Equals;
                column.Settings.ShowFilterRowMenu = DefaultBoolean.False;
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
                column.Settings.SortMode = DevExpress.XtraGrid.ColumnSortMode.Custom;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Bezeichnung";
                column.FieldName = "Description";
                column.MinWidth = 220;
                column.Width = new Unit(250, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Baustelle";
                column.FieldName = "SiteDescription";
                column.MinWidth = 150;
                column.Width = new Unit(150, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Kst.-Stelle";
                column.FieldName = "SiteCustomNumber";
                column.MinWidth = 120;
                column.Width = new Unit(130, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Mitarbeiter";
                column.FieldName = "UserDescription";
                column.MinWidth = 250;
                column.Width = new Unit(250, UnitType.Pixel);
                column.SetDataItemTemplateContent(c =>
                {
                    var userDescriptions = DataBinder.Eval(c.DataItem, "UserDescriptions") as List<string>;

                    if (userDescriptions != null)
                    {
                        foreach (var description in userDescriptions)
                        {
                            var split = description.Split('|');

                            if (split.Length > 1)
                                html.ViewContext.Writer.Write(
                                    "<span style=\"float: left\">" + split[0] + "</span>" +
                                    "<span style=\"float: right\">" + split[1] + "</span><br />");
                            else
                                html.ViewContext.Writer.Write(
                                    "<span>" + split[0] + "</span><br />");
                        }

                    }
                });
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Nachtrag";
                column.FieldName = "AppendixDescription";
                column.MinWidth = 100;
                column.Width = new Unit(100, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Einreichung";
                column.FieldName = "ReceiptDate";
                column.PropertiesEdit.DisplayFormatString = "dd.MM.yyyy";
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.DateRangePicker;
                column.MinWidth = 110;
                column.Width = new Unit(110, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Tage VA-NT";
                column.FieldName = "DaysReceiptToAppendixOffering";
                column.MinWidth = 100;
                column.Width = new Unit(110, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Schätzung";
                column.FieldName = "Value";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 100;
                column.Width = new Unit(120, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Bewert.";
                column.FieldName = "Percentage";
                column.PropertiesEdit.DisplayFormatString = "p0";
                column.MinWidth = 70;
                column.Width = new Unit(80, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Schätzung bew.";
                column.FieldName = "PercentageValue";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 100;
                column.Width = new Unit(120, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Status";
                column.FieldName = "StatusDescription";
                column.MinWidth = 110;
                column.Width = new Unit(120, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "VA-Kategorien";
                column.FieldName = "DisturbanceValuesDescription";
                column.MinWidth = 190;
                column.Width = new Unit(220, UnitType.Pixel);
                column.SetFilterTemplateContent(f =>
                {
                    html.DevExpress().TextBox(t =>
                    {
                        t.Name = "devTextBoxFilterDisturbanceValuesDescription";
                        t.Width = new Unit(100, UnitType.Percentage);
                        t.Properties.ClientSideEvents.Init =
                            "function (s, e) { " +
                            "   if (customFilters != null && customFilters['DisturbanceValuesDescription'] != null) {" +
                            "       s.SetText(customFilters['DisturbanceValuesDescription']); }}";
                        t.Properties.ClientSideEvents.KeyUp =
                            "function (s, e) { " +
                            "   customFilters['DisturbanceValuesDescription'] = s.GetValue(); " +
                            "   setFilterTimer(customFilterDelay, function () { devGridViewDeviation.PerformCallback(); }); }";
                    }).Render();
                });
                column.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
                column.UnboundExpression = "[DisturbanceValueSum]";
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Art";
                column.FieldName = "KindDescription";
                column.MinWidth = 140;
                column.Width = new Unit(140, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Kommentar";
                column.FieldName = "Comment";
                column.CellStyle.Wrap = DefaultBoolean.True;
                column.SetDataItemTemplateContent(c =>
                {
                    var id = Convert.ToInt32(DataBinder.Eval(c.DataItem, "Id"));

                    var comment = DataBinder.Eval(c.DataItem, "Comment");
                    var text = comment == null
                        ? String.Empty
                        : comment.ToString();
                    var isLongText = text.ToString().Length > 40;

                    if (isLongText)
                    {
                        html.ViewContext.Writer.Write(text.Substring(0, 40) + " ...");
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick='showComment(\"deviation\"," + id + ",this)'><br />Anzeigen</a>");
                    }
                    else
                        html.ViewContext.Writer.Write(text);

                    if (_userContext.CurrentUser.HasFunction("Deviation-Deviations-Edit-Comment"))
                        html.ViewContext.Writer.Write(
                            (isLongText ? "&nbsp;" : "<br/>") +
                            "&nbsp;<a href=\"#\" onclick='editComment(\"deviation\"," + id + ",function() { devGridViewDeviation.PerformCallback(); })'>Bearbeiten</a>");
                });
                column.MinWidth = 180;
                column.Width = new Unit(180, UnitType.Pixel);
            });

            //s.SetDataRowTemplateContent(t =>
            //{
            //    var list = t.Grid.DataSource as List<DeviationDataModel>;
            //    var model = list.First(l => l.Id == (int)t.KeyValue);

            //    html.RenderPartial("~/Views/Deviations/_DeviationDataRowPartial.cshtml", model, html.ViewData);
            //});

            var totalDaysReceiptToAppendixOfferingSum = 0;
            var totalDaysReceiptToAppendixOfferingCount = 0;

            var totalDisturbanceSum = default(decimal);

            var totalPercentageValueSumZeroSummarize = default(decimal);

            s.CustomSummaryCalculate = (sender, e) =>
            {
                if (e.SummaryProcess == CustomSummaryProcess.Start)
                {
                    totalDaysReceiptToAppendixOfferingSum = 0;
                    totalDaysReceiptToAppendixOfferingCount = 0;

                    totalDisturbanceSum = 0;

                    totalPercentageValueSumZeroSummarize = 0;
                }

                if (e.SummaryProcess == CustomSummaryProcess.Calculate)
                {
                    var daysReceiptToAppendixOfferingVal = e.GetValue("DaysReceiptToAppendixOffering");

                    if (daysReceiptToAppendixOfferingVal != null)
                    {
                        totalDaysReceiptToAppendixOfferingCount++;
                        totalDaysReceiptToAppendixOfferingSum += Convert.ToInt32(daysReceiptToAppendixOfferingVal);
                    }

                    var disturbanceVal = e.GetValue("DisturbanceValueSum");

                    if (disturbanceVal != null)
                        totalDisturbanceSum += Convert.ToDecimal(disturbanceVal);

                    var isZeroValueSum = e.GetValue("IsZeroSummarize");

                    if (isZeroValueSum == null || (isZeroValueSum != null && !Convert.ToBoolean(isZeroValueSum)))
                    {
                        var percentageValue = e.GetValue("PercentageValue");

                        if (percentageValue != null)
                            totalPercentageValueSumZeroSummarize += (decimal)percentageValue;
                    }
                }

                if (e.SummaryProcess == CustomSummaryProcess.Finalize)
                {
                    var summaryItem = (ASPxSummaryItem)e.Item;

                    if (summaryItem.FieldName == "DaysReceiptToAppendixOffering")
                    {
                        if (totalDaysReceiptToAppendixOfferingSum == 0 || totalDaysReceiptToAppendixOfferingCount == 0)
                            e.TotalValue = 0;
                        else
                            e.TotalValue = totalDaysReceiptToAppendixOfferingSum / totalDaysReceiptToAppendixOfferingCount;
                    }
                    else if (summaryItem.FieldName == "DisturbanceValuesDescription")
                        e.TotalValue = totalDisturbanceSum;
                    else if (summaryItem.FieldName == "StatusDescription")
                        e.TotalValue = totalPercentageValueSumZeroSummarize;
                }
            };

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Count,
                FieldName = "SiteDescription",
                DisplayFormat = "Anzahl<br/><i>{0:n0}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Count,
                FieldName = "SiteDescription",
                DisplayFormat = "Anzahl = {0:n0}"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "Value",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Schätzung ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "Value",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Schätzung ∑ = <i>{0:c2}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "Percentage",
                SummaryType = DevExpress.Data.SummaryItemType.Average,
                DisplayFormat = "Bew. Ø<br/><i>{0:p0}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "Percentage",
                SummaryType = DevExpress.Data.SummaryItemType.Average,
                DisplayFormat = "Bew. Ø = <i>{0:p0}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "PercentageValue",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Schätz. bew. ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "PercentageValue",
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                DisplayFormat = "Schätz. bew. ∑ = <i>{0:c2}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "StatusDescription",
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                DisplayFormat = "Schätz. o. Sta. ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "StatusDescription",
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                DisplayFormat = "Schätz. o. Sta. ∑ = <i>{0:c2}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "DaysReceiptToAppendixOffering",
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                DisplayFormat = "T. VA-NT Ø<br/><i>{0:n0}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "DaysReceiptToAppendixOffering",
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                DisplayFormat = "Tage VA-NT Ø = <i>{0:n0}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "DisturbanceValuesDescription",
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                DisplayFormat = "Kat. ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "DisturbanceValuesDescription",
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                DisplayFormat = "Kat. ∑ = <i>{0:c2}</i>"
            });

            s.HtmlRowPrepared = (sender, e) =>
            {
                var displayColor = e.GetValue("DisplayColor");

                if (displayColor != null && e.RowType == GridViewRowType.Data)
                    e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml(displayColor.ToString());
            };

            s.ClientLayout = (sender, e) =>
            {
                if (e.LayoutMode == ClientLayoutMode.Loading)
                {
                    if (System.Web.HttpContext.Current.Session["DeviationGridState"] != null)
                        e.LayoutData = (string)System.Web.HttpContext.Current.Session["DeviationGridState"];
                    else
                    {
                        var userConfigItem = _configurationService.GetUserConfigItemByNameAndUserId("DeviationGridLayoutState",
                            _userContext.CurrentUser.Id);

                        if (userConfigItem != null)
                        {
                            System.Web.HttpContext.Current.Session["DeviationGridState"] = userConfigItem.Value;

                            e.LayoutData = (string)System.Web.HttpContext.Current.Session["DeviationGridState"];
                        }
                        else
                            ((MVCxGridView)sender).SortBy(((MVCxGridView)sender).Columns[0], ColumnSortOrder.Ascending);
                    }
                }
                else
                {
                    System.Web.HttpContext.Current.Session["DeviationGridState"] = e.LayoutData;

                    _configurationService.InsertOrUpdateUserConfigItem(new Core.Domain.Config.UserConfigItem
                    {
                        UserId = _userContext.CurrentUser.Id,
                        Name = "DeviationGridLayoutState",
                        Value = e.LayoutData
                    });
                }
            };

            s.PreRender = s.BeforeGetCallbackResult = (sender, e) => {
                MVCxGridView gridView = sender as MVCxGridView;
                System.Web.HttpContext.Current.Session["DeviationGridViewState"] = new MVCxGridViewState(gridView);
            };

            s.CustomColumnSort = (sender, e) =>
            {
                if (e.Column.FieldName != "CustomNumber") return;

                int.TryParse(e.GetRow1Value("CustomNumber").ToString(), out int rowVal1);
                int.TryParse(e.GetRow2Value("CustomNumber").ToString(), out int rowVal2);

                e.Result = (rowVal1).CompareTo(rowVal2);

                e.Handled = true;
            };

            s.ClientSideEvents.BeginCallback = "function (s, e) { " +
                "e.customArgs['scrollHeight'] = [ gridScrollHeight ]; " +
                "e.customArgs['customFilters'] = [ JSON.stringify(customFilters) ]; }";
            s.ClientSideEvents.ToolbarItemClick = "function (s, e) { onToolbarItemClick(s, e); }";

            s.Styles.Footer.CssClass += "devExGridFooterPanel";
            s.Styles.GroupRow.CssClass += "devExGridGroupRow";

            s.Styles.AlternatingRow.BackColor = System.Drawing.Color.FromArgb(247, 247, 247);

            return s;
        }

        /// <summary>
        /// Creates GridViewSettings for the appendix gridView
        /// </summary>
        /// <param name="html">Current HtmlHelper context.</param>
        public static GridViewSettings AppendixGridViewSettings(this System.Web.Mvc.HtmlHelper html)
        {
            var s = new GridViewSettings();

            s.Name = "devGridViewAppendix";
            s.KeyFieldName = "Id";
            s.CallbackRouteValues = new { Controller = "Appendix", Action = "PartialAppendices" };
            s.Width = Unit.Percentage(99);
            s.Settings.ShowHeaderFilterButton = true;
            s.Settings.ShowFilterRow = true;
            s.Settings.ShowFilterRowMenu = true;
            s.Settings.ShowFooter = true;
            s.Settings.ShowGroupPanel = true;
            s.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
            s.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollableHeight =
                (html.ViewData["ScrollHeight"] == null || (int)html.ViewData["ScrollHeight"] == -1)
                ? 400
                : (int)html.ViewData["ScrollHeight"];
            s.SettingsExport.Landscape = true;
            s.SettingsExport.FileName = "Nachtragsliste";
            s.SettingsPopup.CustomizationWindow.Width = new Unit(250, UnitType.Pixel);
            s.SettingsPopup.CustomizationWindow.Height = new Unit(350, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Width = new Unit(353, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Height = new Unit(360, UnitType.Pixel);
            s.SettingsBehavior.EnableCustomizationWindow = true;
            s.SettingsBehavior.AllowHeaderFilter = true;
            s.SettingsPager.AlwaysShowPager = true;
            s.SettingsResizing.ColumnResizeMode = ColumnResizeMode.Control;
            s.SettingsPager.Position = PagerPosition.Bottom;
            s.SettingsPager.PageSizeItemSettings.Visible = true;
            s.SettingsPager.FirstPageButton.Visible = true;
            s.SettingsPager.LastPageButton.Visible = true;
            s.SettingsPager.NumericButtonCount = 5;

            s.Toolbars.Add(t =>
            {
                var refreshItem = t.Items.Add(GridViewToolbarCommand.Refresh);
                refreshItem.Text = "Aktualisieren";
                var expandItem = t.Items.Add(GridViewToolbarCommand.FullExpand);
                expandItem.Text = "Alle aufklappen";
                var collapseItem = t.Items.Add(GridViewToolbarCommand.FullCollapse);
                collapseItem.Text = "Alle einklappen";
                var filterItem = t.Items.Add(GridViewToolbarCommand.ClearFilter);
                filterItem.Text = "Filter entfernen";
                t.Items.Add(i =>
                {
                    i.Text = "Spalten anzeigen / ausblenden";
                    i.Name = "ToggleColumnChooser";
                    i.Image.IconID = IconID.OtherViewgridlines16x16gray;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Drucken";
                    i.Name = "Print";
                    i.Image.IconID = IconID.PrintDefaultprinter16x16;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Zurücksetzen";
                    i.Name = "ResetSettings";
                    i.Image.IconID = IconID.ActionsReset16x16;
                    i.BeginGroup = true;
                });
            });

            s.Columns.Add(column =>
            {
                column.Caption = "#";
                column.FieldName = "CustomNumber";
                column.MinWidth = 80;
                column.Width = new Unit(80, UnitType.Pixel);
                column.Settings.AutoFilterCondition = AutoFilterCondition.Equals;
                column.Settings.ShowFilterRowMenu = DefaultBoolean.False;
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
                column.Settings.SortMode = DevExpress.XtraGrid.ColumnSortMode.Custom;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Bezeichnung";
                column.FieldName = "Description";
                column.MinWidth = 200;
                column.Width = new Unit(200, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
                column.SetDataItemTemplateContent(c =>
                {
                    var id = Convert.ToInt32(DataBinder.Eval(c.DataItem, "Id"));
                    var description = DataBinder.Eval(c.DataItem, "Description");

                    html.ViewContext.Writer.Write(description +
                        "<br/><a href=\"#\" onclick='viewAppendix(" + id + ")'>Details anzeigen</a>");
                });
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Baustelle";
                column.FieldName = "SiteDescription";
                column.MinWidth = 150;
                column.Width = new Unit(150, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Kst.-Stelle";
                column.FieldName = "SiteCustomNumber";
                column.MinWidth = 120;
                column.Width = new Unit(120, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Mitarbeiter";
                column.FieldName = "UserDescription";
                column.MinWidth = 245;
                column.Width = new Unit(245, UnitType.Pixel);
                column.SetDataItemTemplateContent(c =>
                {
                    var userDescriptions = DataBinder.Eval(c.DataItem, "UserDescriptions") as List<string>;

                    if (userDescriptions != null)
                    {
                        foreach (var description in userDescriptions)
                        {
                            var split = description.Split('|');

                            if (split.Length > 1)
                                html.ViewContext.Writer.Write(
                                    "<span style=\"float: left\">" + split[0] + "</span>" +
                                    "<span style=\"float: right\">" + split[1] + "</span><br />");
                            else
                                html.ViewContext.Writer.Write(
                                    "<span>" + split[0] + "</span><br />");
                        }

                    }
                });
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Einreichung";
                column.FieldName = "OfferingDate";
                column.PropertiesEdit.DisplayFormatString = "dd.MM.yyyy";
                column.MinWidth = 100;
                column.Width = new Unit(110, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Angeb. -Summe";
                column.FieldName = "OfferingValue";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 100;
                column.Width = new Unit(110, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Bewert.";
                column.FieldName = "Percentage";
                column.PropertiesEdit.DisplayFormatString = "p0";
                column.MinWidth = 70;
                column.Width = new Unit(60, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Angebot bew.";
                column.FieldName = "PercentageValue";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 100;
                column.Width = new Unit(120, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Verhand. -Summe";
                column.FieldName = "NegotiationValue";
                column.PropertiesEdit.DisplayFormatString = "c2";
                column.MinWidth = 110;
                column.Width = new Unit(110, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Verh.-Quote";
                column.FieldName = "RelationOfferingToNegotiation";
                column.PropertiesEdit.DisplayFormatString = "p2";
                column.MinWidth = 115;
                column.Width = new Unit(115, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "VA";
                column.FieldName = "DeviationDescription";
                column.MinWidth = 80;
                column.Width = new Unit(80, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Fak. Ang. zu VA";
                column.FieldName = "RelationOfferingToDeviations";
                column.PropertiesEdit.DisplayFormatString = "n2";
                column.MinWidth = 100;
                column.Width = new Unit(100, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "AR gestellt";
                column.FieldName = "OrderInvoiceCreatedDescription";
                column.MinWidth = 60;
                column.Width = new Unit(80, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
                column.SetDataItemTemplateContent(c =>
                {
                    var id = Convert.ToInt32(DataBinder.Eval(c.DataItem, "Id"));
                    var description = DataBinder.Eval(c.DataItem, "OrderInvoiceCreatedDescription");

                    if (_userContext.CurrentUser.HasFunction("Appendix-Appendices-Edit"))
                        html.ViewContext.Writer.Write(description +
                            "<br/><a href=\"#\" onclick='editOrderInvoiceCreated(" + id + "," +
                            "   function() { devGridViewAppendix.PerformCallback(); })'>Ändern</a>");
                });
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Status";
                column.FieldName = "StateDescription";
                column.MinWidth = 100;
                column.Width = new Unit(100, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Bestellsch.-Datum";
                column.FieldName = "OrderDate";
                column.PropertiesEdit.DisplayFormatString = "dd.MM.yyyy";
                column.MinWidth = 110;
                column.Width = new Unit(110, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Bestellsch.-Nummer";
                column.FieldName = "OrderNumber";
                column.MinWidth = 90;
                column.Width = new Unit(110, UnitType.Pixel);
                column.HeaderStyle.Wrap = DefaultBoolean.True;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "NT-Kategorien";
                column.FieldName = "CategoryValuesDescription";
                column.MinWidth = 200;
                column.Width = new Unit(200, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Kommentar";
                column.FieldName = "Comment";
                column.CellStyle.Wrap = DefaultBoolean.True;
                column.SetDataItemTemplateContent(c =>
                {
                    var id = Convert.ToInt32(DataBinder.Eval(c.DataItem, "Id"));

                    var comment = DataBinder.Eval(c.DataItem, "Comment");
                    var text = comment == null
                        ? String.Empty
                        : comment.ToString();
                    var isLongText = text.ToString().Length > 40;

                    if (isLongText)
                    {
                        html.ViewContext.Writer.Write(text.Substring(0, 40) + " ...");
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick='showComment(\"appendix\"," + id + ",this)'><br />Anzeigen</a>");
                    }
                    else
                        html.ViewContext.Writer.Write(text);

                    if (_userContext.CurrentUser.HasFunction("Deviation-Deviations-Edit-Comment"))
                        html.ViewContext.Writer.Write(
                            (isLongText ? "&nbsp;" : "<br/>") +
                            "<a href=\"#\" onclick='editComment(\"appendix\"," + id + ",function() { devGridViewAppendix.PerformCallback(); })'>Bearbeiten</a>");
                });
                column.MinWidth = 200;
                column.Width = new Unit(200, UnitType.Pixel);
            });

            var totalRelationOfferingToDeviationsSum = (decimal)0;
            var totalRelationOfferingToDeviationsCount = 0;

            var totalPercentageValueSum = (decimal)0;
            var totalNegotiationValueSum = (decimal)0;

            s.CustomSummaryCalculate = (sender, e) =>
            {
                if (e.SummaryProcess == CustomSummaryProcess.Start)
                {
                    totalRelationOfferingToDeviationsSum = 0;
                    totalRelationOfferingToDeviationsCount = 0;

                    totalPercentageValueSum = 0;
                    totalNegotiationValueSum = 0;
                }

                if (e.SummaryProcess == CustomSummaryProcess.Calculate)
                {
                    var relationOfferingToDeviationsVal = e.GetValue("RelationOfferingToDeviations");

                    if (relationOfferingToDeviationsVal != null)
                    {
                        totalRelationOfferingToDeviationsCount++;
                        totalRelationOfferingToDeviationsSum += Convert.ToDecimal(relationOfferingToDeviationsVal);
                    }

                    var percentageVal = e.GetValue("PercentageValue");

                    if (percentageVal != null)
                        totalPercentageValueSum += Convert.ToDecimal(percentageVal);

                    var negotiationVal = e.GetValue("NegotiationValue");

                    if (negotiationVal != null)
                        totalNegotiationValueSum += Convert.ToDecimal(negotiationVal);
                }

                if (e.SummaryProcess == CustomSummaryProcess.Finalize)
                {
                    var summaryItem = (ASPxSummaryItem)e.Item;

                    if (summaryItem.FieldName == "PercentageValue")
                        e.TotalValue = totalPercentageValueSum;

                    if (summaryItem.FieldName == "NegotiationValue")
                        e.TotalValue = totalNegotiationValueSum;

                    if (summaryItem.FieldName == "RelationOfferingToDeviations")
                    {
                        if (totalRelationOfferingToDeviationsSum == 0 || totalRelationOfferingToDeviationsCount == 0)
                            e.TotalValue = 0;
                        else
                            e.TotalValue = 
                                totalRelationOfferingToDeviationsSum / 
                                    (totalRelationOfferingToDeviationsCount == 0
                                        ? 1
                                        : totalRelationOfferingToDeviationsCount);
                    }

                    if (summaryItem.FieldName == "RelationOfferingToNegotiation")
                        e.TotalValue = 
                            totalNegotiationValueSum / 
                                (totalPercentageValueSum == 0 
                                    ? 1 
                                    : totalPercentageValueSum);
                }
            };

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Count,
                FieldName = "Description",
                DisplayFormat = "Anzahl<br/><i>{0:n0}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Count,
                FieldName = "Description",
                DisplayFormat = "Anzahl = {0:n0}"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                FieldName = "OfferingValue",
                DisplayFormat = "Angeb. ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Sum,
                FieldName = "OfferingValue",
                DisplayFormat = "Angeb.-∑ = {0:c2}"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "Percentage",
                SummaryType = DevExpress.Data.SummaryItemType.Average,
                DisplayFormat = "Bew. Ø<br/><i>{0:p0}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "Percentage",
                SummaryType = DevExpress.Data.SummaryItemType.Average,
                DisplayFormat = "Bew. Ø = <i>{0:p0}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                FieldName = "PercentageValue",
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                DisplayFormat = "Schätz. bew. ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                FieldName = "PercentageValue",
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                DisplayFormat = "Schätz. bew. ∑ = <i>{0:c2}</i>"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                FieldName = "NegotiationValue",
                DisplayFormat = "Verhand. ∑<br/><i>{0:c2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                FieldName = "NegotiationValue",
                DisplayFormat = "Verhand.-∑ = {0:c2}"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                FieldName = "RelationOfferingToNegotiation",
                DisplayFormat = "Verh. Quo. Ø<br/><i>{0:p2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                FieldName = "RelationOfferingToNegotiation",
                DisplayFormat = "Verh. Quo. Ø = {0:p2}"
            });

            s.TotalSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                FieldName = "RelationOfferingToDeviations",
                DisplayFormat = "Fak. A./VA Ø<br/><i>{0:n2}</i>"
            });
            s.GroupSummary.Add(new ASPxSummaryItem
            {
                SummaryType = DevExpress.Data.SummaryItemType.Custom,
                FieldName = "RelationOfferingToDeviations",
                DisplayFormat = "Fak. A./VA Ø = {0:n2}"
            });

            s.HtmlRowPrepared = (sender, e) =>
            {
                var state = e.GetValue("State") as StateDataModel;

                if (e.RowType == GridViewRowType.Data && state != null && !state.IsDefault)
                    e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml(state.HexColor);
            };

            s.ClientLayout = (sender, e) =>
            {
                if (e.LayoutMode == ClientLayoutMode.Loading)
                {
                    if (System.Web.HttpContext.Current.Session["AppendixGridState"] != null)
                        e.LayoutData = (string)System.Web.HttpContext.Current.Session["AppendixGridState"];
                    else
                    {
                        var userConfigItem = _configurationService.GetUserConfigItemByNameAndUserId("AppendixGridLayoutState",
                            _userContext.CurrentUser.Id);

                        if (userConfigItem != null)
                        {
                            System.Web.HttpContext.Current.Session["AppendixGridState"] = userConfigItem.Value;

                            e.LayoutData = (string)System.Web.HttpContext.Current.Session["AppendixGridState"];
                        }
                        else
                            ((MVCxGridView)sender).SortBy(((MVCxGridView)sender).Columns[0], ColumnSortOrder.Ascending);
                    }
                }
                else
                {
                    System.Web.HttpContext.Current.Session["AppendixGridState"] = e.LayoutData;

                    _configurationService.InsertOrUpdateUserConfigItem(new Core.Domain.Config.UserConfigItem
                    {
                        UserId = _userContext.CurrentUser.Id,
                        Name = "AppendixGridLayoutState",
                        Value = e.LayoutData
                    });
                }
            };

            s.PreRender = s.BeforeGetCallbackResult = (sender, e) => {
                MVCxGridView gridView = sender as MVCxGridView;
                System.Web.HttpContext.Current.Session["AppendixGridViewState"] = new MVCxGridViewState(gridView);
            };

            s.CustomColumnSort = (sender, e) =>
            {
                if (e.Column.FieldName != "CustomNumber") return;

                int.TryParse(e.GetRow1Value("CustomNumber").ToString(), out int rowVal1);
                int.TryParse(e.GetRow2Value("CustomNumber").ToString(), out int rowVal2);

                e.Result = (rowVal1).CompareTo(rowVal2);

                e.Handled = true;
            };

            s.ClientSideEvents.BeginCallback = "function (s, e) { e.customArgs['scrollHeight'] = [ gridScrollHeight ]; }";
            s.ClientSideEvents.ToolbarItemClick = "function (s, e) { onToolbarItemClick(s, e); }";
            s.ClientSideEvents.ColumnResized = "function (s, e) { setGridScrollHeight(); }";

            //s.Styles.AlternatingRow.BackColor = System.Drawing.Color.FromArgb(247, 247, 247);

            s.Styles.Footer.CssClass += "devExGridFooterPanel";
            s.Styles.GroupRow.CssClass += "devExGridGroupRow";

            return s;
        }

        /// <summary>
        /// Creates GridViewSettings for the mailNotifications gridView
        /// </summary>
        /// <param name="html">Current HtmlHelper context.</param>
        public static GridViewSettings MailNotificationGridViewSettings(this System.Web.Mvc.HtmlHelper html)
        {
            var s = new GridViewSettings();

            s.Name = "devGridViewMailNotifications";
            s.KeyFieldName = "Id";
            s.CallbackRouteValues = new { Controller = "Misc", Action = "PartialMailNotifications" };
            s.Width = Unit.Percentage(99);
            s.Settings.ShowHeaderFilterButton = true;
            s.Settings.ShowFilterRow = true;
            s.Settings.ShowFilterRowMenu = true;
            s.Settings.ShowFooter = true;
            s.Settings.ShowGroupPanel = true;
            s.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
            s.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollableHeight =
                (html.ViewData["ScrollHeight"] == null || (int)html.ViewData["ScrollHeight"] == -1)
                ? 400
                : (int)html.ViewData["ScrollHeight"];
            s.SettingsExport.Landscape = true;
            s.SettingsExport.FileName = "Benachrichtigungsliste";
            s.SettingsPopup.CustomizationWindow.Width = new Unit(250, UnitType.Pixel);
            s.SettingsPopup.CustomizationWindow.Height = new Unit(350, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Width = new Unit(353, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Height = new Unit(360, UnitType.Pixel);
            s.SettingsBehavior.EnableCustomizationWindow = true;
            s.SettingsBehavior.AllowHeaderFilter = true;
            s.SettingsPager.AlwaysShowPager = true;
            s.SettingsResizing.ColumnResizeMode = ColumnResizeMode.Control;
            s.SettingsPager.Position = PagerPosition.Bottom;
            s.SettingsPager.PageSizeItemSettings.Visible = true;
            s.SettingsPager.FirstPageButton.Visible = true;
            s.SettingsPager.LastPageButton.Visible = true;
            s.SettingsPager.NumericButtonCount = 5;

            s.Toolbars.Add(t =>
            {
                var refreshItem = t.Items.Add(GridViewToolbarCommand.Refresh);
                refreshItem.Text = "Aktualisieren";
                var filterItem = t.Items.Add(GridViewToolbarCommand.ClearFilter);
                filterItem.Text = "Filter entfernen";
                t.Items.Add(i =>
                {
                    i.Text = "Spalten anzeigen / ausblenden";
                    i.Name = "ToggleColumnChooser";
                    i.Image.IconID = IconID.OtherViewgridlines16x16gray;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Zurücksetzen";
                    i.Name = "ResetSettings";
                    i.Image.IconID = IconID.ActionsReset16x16;
                    i.BeginGroup = true;
                });
            });

            if (_userContext.CurrentUser.HasFunction("Misc-MailNotifications-Edit"))
            {
                s.Columns.Add(column =>
                {
                    column.Caption = "#";
                    column.SetDataItemTemplateContent(c =>
                    {
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick=\"editMailNotification(" + DataBinder.Eval(c.DataItem, "Id") + ")\">Bearbeiten</a>&nbsp;");
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick=\"confirmDelete(" + DataBinder.Eval(c.DataItem, "Id") + ")\">Löschen</a><br />");
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick=\"confirmProcess(" + DataBinder.Eval(c.DataItem, "Id") + ")\">Sofort ausführen</a>");
                    });
                    column.SetHeaderTemplateContent(c =>
                    {
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick=\"editMailNotification(-1)\">Neu</a>&nbsp;");
                    });
                    column.Settings.AllowDragDrop = DefaultBoolean.False;
                    column.Settings.AllowSort = DefaultBoolean.False;
                    column.Width = new Unit(150, UnitType.Pixel);
                });
            }
            s.Columns.Add(column =>
            {
                column.Caption = "Zeitplan";
                column.FieldName = "CronExpressionDescription";
                column.MinWidth = 200;
                column.Width = new Unit(200, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Benachrichtigungs-Plugin";
                column.FieldName = "NotificationPluginSystemNameDescription";
                column.Width = new Unit(180, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Benachrichtigungs-Job";
                column.FieldName = "NotificationJobSystemNameDescription";
                column.PropertiesEdit.DisplayFormatString = "dd.MM.yyyy";
                column.MinWidth = 180;
                column.Width = new Unit(180, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Mitarbeiter";
                column.FieldName = "UserDescriptions";
                column.MinWidth = 150;
                column.Width = new Unit(200, UnitType.Pixel);
                column.SetDataItemTemplateContent(c =>
                {
                    var userDescriptions = DataBinder.Eval(c.DataItem, "UserDescriptions") as List<string>;

                    if (userDescriptions != null)
                    {
                        foreach (var description in userDescriptions)
                        {
                            var split = description.Split('|');

                            if (split.Length > 1)
                                html.ViewContext.Writer.Write(
                                    "<span style=\"float: left\">" + split[0] + "</span>" +
                                    "<span style=\"float: right\">" + split[1] + "</span><br />");
                            else
                                html.ViewContext.Writer.Write(
                                    "<span>" + split[0] + "</span><br />");
                        }

                    }
                });
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Nächste Ausführung";
                column.FieldName = "NextExecutionTime";
                column.PropertiesEdit.DisplayFormatString = "dd.MM.yyyy";
                column.MinWidth = 110;
                column.Width = new Unit(150, UnitType.Pixel);
            });

            s.ClientLayout = (sender, e) =>
            {
                if (e.LayoutMode == ClientLayoutMode.Loading)
                {
                    if (System.Web.HttpContext.Current.Session["MailNotificationsGridState"] != null)
                        e.LayoutData = (string)System.Web.HttpContext.Current.Session["MailNotificationsGridState"];
                    else
                    {
                        var userConfigItem = _configurationService.GetUserConfigItemByNameAndUserId("MailNotificationsGridLayoutState",
                            _userContext.CurrentUser.Id);

                        if (userConfigItem != null)
                        {
                            System.Web.HttpContext.Current.Session["MailNotificationsGridState"] = userConfigItem.Value;

                            e.LayoutData = (string)System.Web.HttpContext.Current.Session["MailNotificationsGridState"];
                        }
                    }
                }
                else
                {
                    System.Web.HttpContext.Current.Session["MailNotificationsGridState"] = e.LayoutData;

                    _configurationService.InsertOrUpdateUserConfigItem(new Core.Domain.Config.UserConfigItem
                    {
                        UserId = _userContext.CurrentUser.Id,
                        Name = "MailNotificationsGridLayoutState",
                        Value = e.LayoutData
                    });
                }
            };
            s.ClientSideEvents.BeginCallback = "function (s, e) { e.customArgs['scrollHeight'] = [ gridScrollHeight ]; }";
            s.ClientSideEvents.ToolbarItemClick = "function (s, e) { onToolbarItemClick(s, e); }";

            s.Styles.AlternatingRow.BackColor = System.Drawing.Color.FromArgb(247, 247, 247);

            return s;
        }

        /// <summary>
        /// Creates GridViewSettings for the logs gridView
        /// </summary>
        /// <param name="html">Current HtmlHelper context.</param>
        public static GridViewSettings LogGridViewSettings(this System.Web.Mvc.HtmlHelper html)
        {
            var s = new GridViewSettings();

            s.Name = "devGridViewLog";
            s.KeyFieldName = "Id";
            s.CallbackRouteValues = new { Controller = "Misc", Action = "PartialLogs" };
            s.Width = Unit.Percentage(99);
            s.Settings.ShowHeaderFilterButton = true;
            s.Settings.ShowFilterRow = true;
            s.Settings.ShowFilterRowMenu = true;
            s.Settings.ShowFooter = true;
            s.Settings.ShowGroupPanel = true;
            s.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
            s.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
            s.Settings.VerticalScrollableHeight =
                (html.ViewData["ScrollHeight"] == null || (int)html.ViewData["ScrollHeight"] == -1)
                ? 400
                : (int)html.ViewData["ScrollHeight"];
            s.SettingsExport.Landscape = true;
            s.SettingsExport.FileName = "Logliste";
            s.SettingsPopup.CustomizationWindow.Width = new Unit(250, UnitType.Pixel);
            s.SettingsPopup.CustomizationWindow.Height = new Unit(350, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Width = new Unit(353, UnitType.Pixel);
            s.SettingsPopup.HeaderFilter.Height = new Unit(360, UnitType.Pixel);
            s.SettingsBehavior.EnableCustomizationWindow = true;
            s.SettingsBehavior.AllowHeaderFilter = true;
            s.SettingsPager.AlwaysShowPager = true;
            s.SettingsResizing.ColumnResizeMode = ColumnResizeMode.Control;
            s.SettingsPager.Position = PagerPosition.Bottom;
            s.SettingsPager.PageSizeItemSettings.Visible = true;
            s.SettingsPager.FirstPageButton.Visible = true;
            s.SettingsPager.LastPageButton.Visible = true;
            s.SettingsPager.NumericButtonCount = 5;

            s.Toolbars.Add(t =>
            {
                var refreshItem = t.Items.Add(GridViewToolbarCommand.Refresh);
                refreshItem.Text = "Aktualisieren";
                var filterItem = t.Items.Add(GridViewToolbarCommand.ClearFilter);
                filterItem.Text = "Filter entfernen";
                t.Items.Add(i =>
                {
                    i.Text = "Spalten anzeigen / ausblenden";
                    i.Name = "ToggleColumnChooser";
                    i.Image.IconID = IconID.OtherViewgridlines16x16gray;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Drucken";
                    i.Name = "Print";
                    i.Image.IconID = IconID.PrintDefaultprinter16x16;
                    i.BeginGroup = true;
                });
                t.Items.Add(i =>
                {
                    i.Text = "Zurücksetzen";
                    i.Name = "ResetSettings";
                    i.Image.IconID = IconID.ActionsReset16x16;
                    i.BeginGroup = true;
                });
            });

            s.Columns.Add(column =>
            {
                column.Caption = "#";
                column.SetDataItemTemplateContent(c =>
                {
                    html.ViewContext.Writer.Write(
                        "<a href=\"#\" onclick=\"viewLog(" + DataBinder.Eval(c.DataItem, "Id") + ")\">Betrachten</a>&nbsp;");

                    if (_userContext.CurrentUser.HasFunction("Misc-Logs-Delete"))
                    {
                        html.ViewContext.Writer.Write(
                            "<a href=\"#\" onclick=\"deleteLog(" + DataBinder.Eval(c.DataItem, "Id") + ")\">Löschen</a><br />");
                    }
                });
                column.Settings.AllowDragDrop = DefaultBoolean.False;
                column.Settings.AllowSort = DefaultBoolean.False;
                column.MinWidth = 100;
                column.Width = new Unit(120, UnitType.Pixel);
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Level";
                column.FieldName = "LogLevelDescription";
                column.MinWidth = 100;
                column.Width = new Unit(100, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Betreff";
                column.FieldName = "ShortMessage";
                column.MinWidth = 150;
                column.Width = new Unit(150, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Nachricht";
                column.FieldName = "FullMessage";
                column.MinWidth = 200;
                column.Width = new Unit(200, UnitType.Pixel);
                column.SetDataItemTemplateContent(c =>
                {
                    var fullMessage = DataBinder.Eval(c.DataItem, "FullMessage");
                    var text = fullMessage == null
                        ? String.Empty
                        : fullMessage.ToString();

                    if (text.ToString().Length > 80)
                        html.ViewContext.Writer.Write(text.Substring(0, 80) + " ...");
                    else
                        html.ViewContext.Writer.Write(text);
                });
            });
            s.Columns.Add(column =>
            {
                column.Caption = "IP-Adresse";
                column.FieldName = "IpAddress";
                column.MinWidth = 130;
                column.Width = new Unit(130, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Mitarbeiter";
                column.FieldName = "UserDescription";
                column.MinWidth = 130;
                column.Width = new Unit(130, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Datentyp";
                column.FieldName = "EntityType";
                column.MinWidth = 100;
                column.Width = new Unit(100, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Daten ID";
                column.FieldName = "EntityId";
                column.MinWidth = 100;
                column.Width = new Unit(100, UnitType.Pixel);
                column.SettingsHeaderFilter.Mode = GridHeaderFilterMode.CheckedList;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Seiten URL";
                column.FieldName = "PageUrl";
                column.MinWidth = 150;
                column.Width = new Unit(150, UnitType.Pixel);
                column.Visible = false;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Relative URL";
                column.FieldName = "ReferrerUrl";
                column.MinWidth = 100;
                column.Width = new Unit(100, UnitType.Pixel);
                column.Visible = false;
            });
            s.Columns.Add(column =>
            {
                column.Caption = "Zeitpunkt";
                column.FieldName = "CreatedOnLocal";
                column.PropertiesEdit.DisplayFormatString = "dd.MM.yyyy - HH:mm:ss";
                column.MinWidth = 150;
                column.Width = new Unit(150, UnitType.Pixel);
            });

            s.ClientLayout = (sender, e) =>
            {
                if (e.LayoutMode == ClientLayoutMode.Loading)
                {
                    if (System.Web.HttpContext.Current.Session["LogGridState"] != null)
                        e.LayoutData = (string)System.Web.HttpContext.Current.Session["LogGridState"];
                    else
                    {
                        var userConfigItem = _configurationService.GetUserConfigItemByNameAndUserId("LogGridLayoutState",
                            _userContext.CurrentUser.Id);

                        if (userConfigItem != null)
                        {
                            System.Web.HttpContext.Current.Session["LogGridState"] = userConfigItem.Value;

                            e.LayoutData = (string)System.Web.HttpContext.Current.Session["LogGridState"];
                        }
                    }
                }
                else
                {
                    System.Web.HttpContext.Current.Session["LogGridState"] = e.LayoutData;

                    _configurationService.InsertOrUpdateUserConfigItem(new Core.Domain.Config.UserConfigItem
                    {
                        UserId = _userContext.CurrentUser.Id,
                        Name = "LogGridLayoutState",
                        Value = e.LayoutData
                    });
                }
            };

            s.PreRender = s.BeforeGetCallbackResult = (sender, e) => {
                MVCxGridView gridView = sender as MVCxGridView;
                System.Web.HttpContext.Current.Session["LogGridViewState"] = new MVCxGridViewState(gridView);
            };

            s.ClientSideEvents.BeginCallback = "function (s, e) { e.customArgs['scrollHeight'] = [ gridScrollHeight ]; }";
            s.ClientSideEvents.ToolbarItemClick = "function (s, e) { onToolbarItemClick(s, e); }";

            s.Styles.AlternatingRow.BackColor = System.Drawing.Color.FromArgb(247, 247, 247);

            return s;
        }
    }
}