@using GreenTree.Nachtragsmanagement.Web.Extensions

@{ 
	var userContext = GreenTree.Nachtragsmanagement.Core.CommonHelper.UserContext();
	var disturbanceValues = Model.DisturbanceValueEntities.ToArray();
}

@model GreenTree.Nachtragsmanagement.Web.Models.Deviation.DeviationDataModel

<div class="deviationEditContainer">

	<script>
		var textSeparator = ", ";

		function saveDeviation() {
			DisturbanceEntities.SelectAll();
			var form = $("#deviationEditForm");
			$(form).submit(function (e) {
				PercentageDeviation.SetValue(PercentageDeviation.GetValue() / 100);
				$.ajax({
					type: "POST",
					url: '@Url.Action("EditDeviation", "Deviation")',
					data: form.serialize(),
					success: function (response) {
						setTimeout(function () {
							$(".deviationEditContainer").remove();
							if (response == "success") {
								if (typeof onDeviationSaveSuccess === 'function') {
									onDeviationSaveSuccess();
								}
							} else {
								$("body").append(response);
							}
						}, 200);
					}
				});
				e.preventDefault();
			});
			form.submit();
		}

		function addStatus() {
			$.ajax({
				url: '@Url.Action("EditClaim", "Deviation")',
				data: { claimType: "status", Id: -1 },
				success: function (response) {
					setTimeout(function () {
						$(".claimEditContainer").remove();
						$("body").append(response);
						parent.addCustomEventListener('StatusDataCallbackEventReceiver', function () {
							StatusId.PerformCallback();
						});
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function addDisturbance() {
			$.ajax({
				url: '@Url.Action("EditClaim", "Deviation")',
				data: { claimType: "disturbance", Id: -1 },
				success: function (response) {
					setTimeout(function () {
						$(".claimEditContainer").remove();
						$("body").append(response);
						parent.addCustomEventListener('DisturbanceDataCallbackEventReceiver', function () {
							DisturbanceId.PerformCallback();
						});
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function addKind() {
			$.ajax({
				url: '@Url.Action("EditClaim", "Deviation")',
				data: { claimType: "kind", Id: -1 },
				success: function (response) {
					setTimeout(function () {
						$(".claimEditContainer").remove();
						$("body").append(response);
						parent.addCustomEventListener('KindDataCallbackEventReceiver', function () {
							KindId.PerformCallback();
						});
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function setDropDownText() {
			var allItems = DisturbanceEntities.GetItemCount();
			var text = "";
			for (var i = 0; i < allItems; i++) {
				if (i == allItems - 1) {
					text += JSON.parse(DisturbanceEntities.GetItem(i).value).Description;
				} else {
					text += JSON.parse(DisturbanceEntities.GetItem(i).value).Description + ", ";
				}
			}
			devDropDownListDisturbanceValues.SetText(text);
		}

		function addDisturbanceValue() {
			var distVal = {
				DisturbanceId: devListBoxAllDisturbances.GetValue(),
				Description: devListBoxAllDisturbances.GetSelectedItem().text + " - " + devSpinEditDisturbanceValue.GetText(),
				Value: devSpinEditDisturbanceValue.GetValue()
			};
			var distValJson = JSON.stringify(distVal);
			var listBox = MVCxClientListBox.Cast(DisturbanceEntities);
			listBox.AddItem(distVal.Description + "<a style=\"float: right\" href=\"#\" onclick='removeDisturbanceValue(\"" + distVal.Description + "\")'>Entfernen</a>", distValJson);
			devDisturbanceValuePopup.Hide();
			setDropDownText();
		}

		function removeDisturbanceValue(description) {
			var allItems = DisturbanceEntities.GetItemCount();
			for (var i = 0; i < allItems; i++) {
				var item = DisturbanceEntities.GetItem(i);
				if (item.text.indexOf(description) != -1) {
					DisturbanceEntities.RemoveItem(i);
				}
			}
			setDropDownText();
		}

		function calculateValueDeviation() {
			PercentageValueDeviation.SetValue((ValueDeviation.GetValue() / 100) * PercentageDeviation.GetValue());
		}
	</script>

	@Html.Partial("~/Views/Deviations/_DisturbanceValueEditPartial.cshtml")

	@Html.DevExpress().PopupControl(s =>
{
	s.Name = "devPopupControlEditDeviation";

	if (Model.Id == -1)
		s.HeaderText = "Neue Vertragsabweichung erstellen";
	else
		s.HeaderText = "\"" + Model.CustomNumber + "\" bearbeiten";

	s.Modal = true;
	s.Width = new Unit(700, UnitType.Pixel);
	s.CloseAction = CloseAction.CloseButton;
	s.PopupHorizontalAlign = PopupHorizontalAlign.WindowCenter;
	s.PopupVerticalAlign = PopupVerticalAlign.TopSides;
	s.PopupVerticalOffset = 15;
	s.AllowDragging = true;
	s.AllowResize = false;
	s.ShowFooter = false;
	s.ShowOnPageLoad = true;
	s.SetContent(() =>
	{
		using (Html.BeginForm("EditDeviation", "Deviation", FormMethod.Post, new { id = "deviationEditForm" }))
		{
			ViewContext.Writer.Write("<div class='editFormWrapper'>");

			ViewContext.Writer.Write("<input type=\"hidden\" value=\"" + Model.Id + "\" id=\"Id\" name=\"Id\" />");
			ViewContext.Writer.Write("<input type=\"hidden\" value=\"" + Model.AppendixId + "\" id=\"AppendixId\" name=\"AppendixId\" />");
			ViewContext.Writer.Write("<input type=\"hidden\" value=\"" + Model.SiteId + "\" id=\"SiteId\" name=\"SiteId\" />");

			ViewContext.Writer.Write(Html.ValidationMessageFor(m => m).ToHtmlString());

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 15%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.CustomNumber, "Nummer:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.CustomNumber).ToHtmlString());
					Html.DevExpress().TextBoxFor(m => m.CustomNumber, t =>
					{
						t.Width = new Unit(80, UnitType.Percentage);
					}).Render();
				}
				ViewContext.Writer.Write("</div>");
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 55%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Description, "Bezeichnung:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Description).ToHtmlString());
					Html.DevExpress().TextBoxFor(m => m.Description, t =>
					{
						t.Width = new Unit(92, UnitType.Percentage);
					}).Render();
				}
				ViewContext.Writer.Write("</div>");
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 30%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.ReceiptDate, "Einreichdatum VA:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.ReceiptDate).ToHtmlString());
					Html.DevExpress().DateEditFor(m => m.ReceiptDate, t =>
					{
						t.Width = new Unit(100, UnitType.Percentage);
					}).Render();
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 40%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.DisturbanceEntities, "Kategorien:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.DisturbanceEntities).ToHtmlString());
					Html.DevExpress().DropDownEdit(t =>
					{
						t.Name = "devDropDownListDisturbanceValues";
						t.Width = new Unit(95, UnitType.Percentage);

						if (Model.DisturbanceValueEntities != null && Model.DisturbanceValueEntities.Any())
							t.Text = String.Join(", ",
								Model.DisturbanceValueEntities
									.Select(d => d.Description));

						t.SetDropDownWindowTemplateContent(l =>
						{
							Html.DevExpress().ListBoxFor(m => m.DisturbanceEntities, lb =>
							{
								lb.Width = new Unit(100, UnitType.Percentage);
								lb.Properties.TextField = "Description";
								lb.Properties.ValueField = "Json";
								lb.Properties.ValueType = typeof(string);
								lb.Properties.EnableClientSideAPI = true;
								lb.Properties.SelectionMode = ListEditSelectionMode.Multiple;
								lb.EncodeHtml = false;
								lb.SetItemTemplateContent(i =>
								{
									var description = DataBinder.Eval(i.DataItem, "Description").ToString();

									ViewContext.Writer.Write(description);
									ViewContext.Writer.Write(
										"<a class=\"disturbanceRemoveLink\" style=\"float: right\" href=\"#\" onclick='removeDisturbanceValue(\"" + description + "\")'>Entfernen</a>");
								});
								lb.ControlStyle.Border.BorderStyle = BorderStyle.None;
							}).BindList(Model.DisturbanceValueEntities).Render();
						});
					}).Render();

					Html.DevExpress().HyperLink(t =>
					{
						t.Name = "devHyperLinkDisturbanceValueAdd";
						t.Properties.Text = "Hinzufügen";
						t.NavigateUrl = "#";
						t.Properties.ClientSideEvents.Click = "function (s, e) { devDisturbanceValuePopup.Show(); }";
						t.Style.Add("line-height", "24px");
					}).Render();
				}
				ViewContext.Writer.Write("</div>");

				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 22%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Value, "Schätzung VA:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Value).ToHtmlString());
					Html.DevExpress().SpinEditFor(m => m.Value, t =>
					{
						t.Width = new Unit(90, UnitType.Percentage);
						t.Properties.ClientInstanceName = "ValueDeviation";
						t.Properties.DecimalPlaces = 2;
						t.Properties.NumberType = SpinEditNumberType.Float;
						t.Properties.DisplayFormatString = "c2";
						t.Properties.ClientSideEvents.ValueChanged = "function (s, e) { calculateValueDeviation(); }";
					}).Render();
				}
				ViewContext.Writer.Write("</div>");

				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 16%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Percentage, "Bewertung (%):"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Percentage).ToHtmlString());
					Html.DevExpress().SpinEditFor(m => m.Percentage, t =>
					{
						t.Width = new Unit(88, UnitType.Percentage);
						t.Properties.ClientInstanceName = "PercentageDeviation";
						t.Properties.MaxValue = 100;
						t.Properties.MinValue = 0;
						t.Properties.Increment = (decimal)1;
						t.Properties.NumberType = SpinEditNumberType.Float;
						t.Properties.NumberFormat = SpinEditNumberFormat.Custom;
						t.Properties.DisplayFormatString = "{0,00} %";
						t.Properties.DisplayFormatInEditMode = true;
						t.Properties.ClientSideEvents.ValueChanged = "function (s, e) { calculateValueDeviation(); }";
						t.Properties.ClientSideEvents.Init = "function (s, e) { calculateValueDeviation(); }";
					}).Bind(Model.Percentage * 100).Render();
				}
				ViewContext.Writer.Write("</div>");
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 22%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.PercentageValue, "Wert:"));
					Html.DevExpress().SpinEditFor(m => m.PercentageValue, t =>
					{
						t.Width = new Unit(100, UnitType.Percentage);
						t.Properties.ClientInstanceName = "PercentageValueDeviation";
						t.Properties.DecimalPlaces = 2;
						t.Properties.NumberType = SpinEditNumberType.Float;
						t.Properties.DisplayFormatString = "c2";
					}).Render();
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 50%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.StatusId, "VA-Status:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.StatusId).ToHtmlString());

					Session.Add("DeviationStatusesComboBoxSettings", new Action<ComboBoxSettings>(a =>
					{
						a.Width = new Unit(95, UnitType.Percentage);
						a.Properties.ValueType = typeof(int);
						a.Properties.ValueField = "Id";
						a.Properties.TextField = "Description";

						var serializedModel = Newtonsoft.Json.JsonConvert.SerializeObject(Model);

						a.CallbackRouteValues = new
						{
							Controller = "DataCallback",
							Action = "StatusesComboBox",
							SettingsKey = "DeviationStatusesComboBoxSettings",
							Model = serializedModel,
							Type = Model.GetType().FullName
						};
					}));
					ViewData.Add("StatusesComboBoxSettings", "DeviationStatusesComboBoxSettings");
					Html.RenderPartial("~/Views/Shared/DataEditorTemplates/_StatusesComboBox.cshtml", Model, ViewData);

					if (userContext.CurrentUser.HasFunction("Deviation-Claims-Edit"))
					{
						Html.DevExpress().HyperLink(t =>
						{
							t.Name = "devHyperLinkStatusEventReceiver";
							t.Properties.Text = "Hinzufügen";
							t.NavigateUrl = "#";
							t.Properties.ClientSideEvents.Click = "function (s, e) { addStatus(); }";
							t.Style.Add("line-height", "24px");
						}).Render();
					}
				}
				ViewContext.Writer.Write("</div>");

				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 50%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.KindId, "Art:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.KindId).ToHtmlString());

					Session.Add("DeviationKindsComboBoxSettings", new Action<ComboBoxSettings>(a =>
					{
						a.Width = new Unit(100, UnitType.Percentage);
						a.Properties.ValueType = typeof(int);
						a.Properties.ValueField = "Id";
						a.Properties.TextField = "Description";

						var serializedModel = Newtonsoft.Json.JsonConvert.SerializeObject(Model);

						a.CallbackRouteValues = new
						{
							Controller = "DataCallback",
							Action = "KindsComboBox",
							SettingsKey = "DeviationKindsComboBoxSettings",
							Model = serializedModel,
							Type = Model.GetType().FullName
						};
					}));
					ViewData.Add("KindsComboBoxSettings", "DeviationKindsComboBoxSettings");
					Html.RenderPartial("~/Views/Shared/DataEditorTemplates/_KindsComboBox.cshtml", Model, ViewData);

					if (userContext.CurrentUser.HasFunction("Deviation-Claims-Edit"))
					{
						Html.DevExpress().HyperLink(t =>
						{
							t.Name = "devHyperLinkKindEventReceiver";
							t.Properties.Text = "Hinzufügen";
							t.NavigateUrl = "#";
							t.Properties.ClientSideEvents.Click = "function (s, e) { addKind(); }";
							t.Style.Add("line-height", "24px");
						}).Render();
					}
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</div>");

			ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Comment, "Kommentar:"));
			ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Comment).ToHtmlString());
			Html.DevExpress().MemoFor(m => m.Comment, t =>
			{
				t.Width = new Unit(100, UnitType.Percentage);
				t.Height = new Unit(90, UnitType.Pixel);
			}).Render();

			ViewContext.Writer.Write("</div>");

			Html.RenderPartial(
				"~/Views/Shared/_PopupButtonPanel.cshtml",
				new GreenTree.Nachtragsmanagement.Web.Models.Global.PopupModel
				{
					PopupName = "devPopupControlEditDeviation",
					AcceptFunction = "function (s, e) { saveDeviation(); }"
				}
			);
		}
	});
	s.Styles.Content.Paddings.Padding = new Unit(0);
	s.Styles.ModalBackground.Opacity = 0;
}).GetHtml()
</div>