@using GreenTree.Nachtragsmanagement.Web.Extensions

@{ 
	var userContext = GreenTree.Nachtragsmanagement.Core.CommonHelper.UserContext();
	var categoryValues = Model.CategoryValueEntities.ToArray();
	var isReadOnly = ViewData["ReadOnly"] != null && Convert.ToBoolean(ViewData["ReadOnly"]);
}

@model GreenTree.Nachtragsmanagement.Web.Models.Appendix.AppendixDataModel

<div class="appendixEditContainer">

	<script>
		var textSeparator = ", ";
		var zeroValueStates =
		[
			@foreach (var state in (IEnumerable<GreenTree.Nachtragsmanagement.Core.Domain.Appendix.State>)ViewData["AllStates"])
			{
				if (state.IsZeroValue)
				{ 
					ViewContext.Writer.Write(state.Id);
				}
			}
		];

		function saveAppendix() {
			CategoryEntities.SelectAll();
			var form = $("#appendixEditForm");
			$(form).submit(function (e) {
				$.ajax({
					type: "POST",
					url: '@Url.Action("EditAppendix", "Appendix")',
					data: form.serialize(),
					success: function (response) {
						setTimeout(function () {
							$(".appendixEditContainer").remove();
							if (response == "success") {
								if (typeof onAppendixSaveSuccess === 'function') {
									onAppendixSaveSuccess();
								}
							} else {
								$("body").append(response);
							}
						}, 200);
					}
				});
				e.preventDefault();
			});
			form.submit();
		}

		function addState() {
			$.ajax({
				url: '@Url.Action("EditState", "Appendix")',
				data: { claimType: "status", Id: -1 },
				success: function (response) {
					setTimeout(function () {
						$(".stateEditContainer").remove();
						$("body").append(response);
						parent.addCustomEventListener('StateDataCallbackEventReceiver', function () {
							StateId.PerformCallback();
						});
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

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

		function editInvoice(id) {
			if (!id) return;
			$.ajax({
				url: '@Url.Action("EditInvoice", "Appendix")',
				data: { AppendixId: @Model.Id, Id: id },
				success: function (response) {
					setTimeout(function () {
						$(".invoiceEditContainer").remove();
						$("body").append(response);
						parent.addCustomEventListener('InvoiceDataCallbackEventReceiver', function () {
							devListBoxInvoices.PerformCallback();
						});
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function deleteInvoice(id) {
			$.ajax({
				type: "POST",
				url: '@Url.Action("DeleteInvoice", "Appendix")',
				data: { Id: id },
				success: function (response) {
					setTimeout(function () {
						devListBoxInvoices.PerformCallback();
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function isZeroValueState() {
			var selectedValue = StateId.GetSelectedItem().value;
			if (!selectedValue) return;
			for (var i = 0; i < zeroValueStates.length; i++) {
				if (zeroValueStates == selectedValue) {
					var controls = ASPxClientControl.GetControlCollection();
					var offeringValue = controls.GetByName("OfferingValue");
					var percentage = controls.GetByName("Percentage");
					var percentageValue = controls.GetByName("PercentageValue");
					offeringValue.SetValue(0.00);
					percentage.SetValue(0.00);
					percentageValue.SetValue(0.00);
					break;
				}
			}
		}

		function setInvoiceDropDownTest() {
			var textArray = $(".invoiceText").map(function () {
				return $(this).text();
			}).get();
			devDropDownListInvoices.SetText(textArray.join(textSeparator));
		}

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

		function addCategoryValue() {
			var distVal = {
				CategoryId: devListBoxAllCategories.GetValue(),
				Description: devListBoxAllCategories.GetSelectedItem().text + " - " + devSpinEditCategoryValue.GetText(),
				Value: devSpinEditCategoryValue.GetValue()
			};
			var distValJson = JSON.stringify(distVal);
			var listBox = MVCxClientListBox.Cast(CategoryEntities);
			listBox.AddItem(distVal.Description + "<a style=\"float: right\" href=\"#\" onclick='removeCategoryValue(\"" + distVal.Description + "\")'>Entfernen</a>", distValJson);
			devCategoryValuePopup.Hide();
			setDropDownText();
		}

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

		function calculateValueAppendix() {
			PercentageValueAppendix.SetValue(OfferingValueAppendix.GetValue() * PercentageAppendix.GetValue());
		}
	</script>

	<style>
		.devHyperLinkEditInvoice {
			margin: 0 4px;
			text-decoration: none;
		}

		.devHyperLinkEditInvoice:hover {
			text-decoration: underline;
		}
	</style>

	@Html.Partial("~/Views/Appendices/_CategoryValueEditPartial.cshtml")

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

	if (Model.Id == -1)
		s.HeaderText = "Neuen Nachtrag 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("EditAppendix", "Appendix", FormMethod.Post, new { id = "appendixEditForm" }))
		{
			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.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(90, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
					}).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(97, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
					}).Render();
				}
				ViewContext.Writer.Write("</div>");
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 30%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.OfferingDate, "Einreichdatum NT:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.OfferingDate).ToHtmlString());
					Html.DevExpress().DateEditFor(m => m.OfferingDate, t =>
					{
						t.Width = new Unit(100, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
					}).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.CategoryEntities, "Kategorien:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.CategoryEntities).ToHtmlString());
					Html.DevExpress().DropDownEdit(t =>
					{
						t.Name = "devDropDownListCategoryValues";
						t.Width = new Unit(96, UnitType.Percentage);
						t.ReadOnly = isReadOnly;

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

						t.SetDropDownWindowTemplateContent(l =>
						{
							Html.DevExpress().ListBoxFor(m => m.CategoryEntities, 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='removeCategoryValue(\"" + description + "\")'>Entfernen</a>");
								});
								lb.ControlStyle.Border.BorderStyle = BorderStyle.None;
							}).BindList(Model.CategoryValueEntities).Render();
						});
					}).Render();

					if (!isReadOnly)
					{
						Html.DevExpress().HyperLink(t =>
						{
							t.Name = "devHyperLinkCategoryValueAdd";
							t.Properties.Text = "Hinzufügen";
							t.NavigateUrl = "#";
							t.Properties.ClientSideEvents.Click = "function (s, e) { devCategoryValuePopup.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.OfferingValue, "Angebotssumme:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.OfferingValue).ToHtmlString());
					Html.DevExpress().SpinEditFor(m => m.OfferingValue, t =>
					{
						t.Width = new Unit(94, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
						t.Properties.ClientInstanceName = "OfferingValueAppendix";
						t.Properties.DecimalPlaces = 2;
						t.Properties.NumberType = SpinEditNumberType.Float;
						t.Properties.DisplayFormatString = "c2";
						t.Properties.ClientSideEvents.ValueChanged = "function (s, e) { calculateValueAppendix(); }";
					}).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.ReadOnly = isReadOnly;
						t.Properties.ClientInstanceName = "PercentageAppendix";
						t.Properties.MaxValue = 1;
						t.Properties.MinValue = 0;
						t.Properties.Increment = (decimal)0.1;
						t.Properties.NumberType = SpinEditNumberType.Float;
						t.Properties.NumberFormat = SpinEditNumberFormat.Percent;
						t.Properties.DisplayFormatString = "p0";
						t.Properties.DisplayFormatInEditMode = true;
						t.Properties.ClientSideEvents.ValueChanged = "function (s, e) { calculateValueAppendix(); }";
					}).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.ReadOnly = isReadOnly;
						t.Properties.ClientInstanceName = "PercentageValueAppendix";
						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: 40%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.NegotiationValue, "Verhandlungssumme:"));
					Html.DevExpress().SpinEditFor(m => m.NegotiationValue, t =>
					{
						t.Width = new Unit(96, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
						t.Properties.DecimalPlaces = 2;
						t.Properties.NumberType = SpinEditNumberType.Float;
						t.Properties.DisplayFormatString = "c2";
					}).Render();
				}
				ViewContext.Writer.Write("</div>");

				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 36.1%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.NegotiationDate, "Verhandlungstermin:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.NegotiationDate).ToHtmlString());
					Html.DevExpress().DateEditFor(m => m.NegotiationDate, t =>
					{
						t.Width = new Unit(100, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
					}).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.OrderNumber, "Bestellschein-Nr.:"));
					Html.DevExpress().TextBoxFor(m => m.OrderNumber, t =>
					{
						t.Width = new Unit(96, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
					}).Render();
				}
				ViewContext.Writer.Write("</div>");

				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 36.1%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.OrderDate, "Bestellscheindatum:"));
					Html.DevExpress().DateEditFor(m => m.OrderDate, t =>
					{
						t.Width = new Unit(100, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
					}).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.StateId, "NT-Status:"));
					ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.StateId).ToHtmlString());

					Session.Add("AppendixStatesComboBoxSettings", new Action<ComboBoxSettings>(t =>
					{
						t.Width = new Unit(96, UnitType.Percentage);
						t.ReadOnly = isReadOnly;
						t.Properties.ValueType = typeof(int);
						t.Properties.ValueField = "Id";
						t.Properties.TextField = "Description";

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

						t.CallbackRouteValues = new
						{
							Controller = "DataCallback",
							Action = "StatesComboBox",
							SettingsKey = "AppendixStatesComboBoxSettings",
							Model = serializedModel,
							Type = Model.GetType().FullName
						};

						t.Properties.ClientSideEvents.SelectedIndexChanged = "function (s, e) { isZeroValueState(); }";
					}));
					ViewData.Add("StatesComboBoxSettings", "AppendixStatesComboBoxSettings");
					Html.RenderPartial("~/Views/Shared/DataEditorTemplates/_StatesComboBox.cshtml", Model, ViewData);

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

				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 60%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Invoices, "Rechnungen:"));

					if (Model.Id == -1)
					{
						ViewContext.Writer.Write("<span style=\"margin-left: 8px; color: red\">Nachtrag muss erst gespeichert werden!</span>");
					}

					Html.DevExpress().DropDownEdit(t =>
					{
						t.Name = "devDropDownListInvoices";
						t.Width = new Unit(100, UnitType.Percentage);
						t.ClientEnabled = Model.Id != -1;

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

						t.SetDropDownWindowTemplateContent(l =>
						{
							Html.RenderPartial("~/Views/Appendices/_InvoiceListPartial.cshtml", Model);
						});
					}).Render();

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

			ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
			{
				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 25%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.ProtocolExists, "Protokoll liegt vor:"));
					ViewContext.Writer.Write("<div style=\"overflow: hidden\">");
					{
						ViewContext.Writer.Write("<div style=\"float: left\">");
						{
							Html.DevExpress().RadioButtonFor(m => m.ProtocolExists, t =>
							{
								t.Text = "Ja";
								t.GroupName = "protocolExists";
								t.ReadOnly = isReadOnly;
							}).Render();
						}
						ViewContext.Writer.Write("</div>");

						ViewContext.Writer.Write("<div style=\"float: left; margin-left: 8px\">");
						{
							Html.DevExpress().RadioButton(t =>
							{
								t.Name = "protocolExistsFalse";
								t.Text = "Nein";
								t.GroupName = "protocolExists";
								t.Checked = !Model.ProtocolExists;
								t.ReadOnly = isReadOnly;
							}).Render();
						}
						ViewContext.Writer.Write("</div>");
					}
					ViewContext.Writer.Write("</div>");
				}
				ViewContext.Writer.Write("</div>");

				ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 25%'>");
				{
					ViewContext.Writer.Write(Html.CustomLabelFor(m => m.OrderInvoiceCreated, "AR gestellt:"));
					ViewContext.Writer.Write("<div style=\"overflow: hidden\">");
					{
						ViewContext.Writer.Write("<div style=\"float: left\">");
						{
							Html.DevExpress().RadioButtonFor(m => m.OrderInvoiceCreated, t =>
							{
								t.Text = "Ja";
								t.GroupName = "orderInvoiceCreated";
								t.ReadOnly = isReadOnly;
							}).Render();
						}
						ViewContext.Writer.Write("</div>");

						ViewContext.Writer.Write("<div style=\"float: left; margin-left: 8px\">");
						{
							Html.DevExpress().RadioButton(t =>
							{
								t.Name = "orderInvoiceCreatedFalse";
								t.Text = "Nein";
								t.GroupName = "orderInvoiceCreated";
								t.Checked = !Model.OrderInvoiceCreated;
								t.ReadOnly = isReadOnly;
							}).Render();
						}
						ViewContext.Writer.Write("</div>");
					}
					ViewContext.Writer.Write("</div>");
				}
				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);
				t.ReadOnly = isReadOnly;
			}).Render();

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

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