@using GreenTree.Nachtragsmanagement.Web.Extensions

@{ 
	var userContext = GreenTree.Nachtragsmanagement.Core.CommonHelper.UserContext();
}

@model GreenTree.Nachtragsmanagement.Web.Models.Site.SiteDataModel

<div class="siteEditContainer">

	<script>
		var textSeparator = ", ";
		var isDragging = false;
		var dragStartY = 0;
		var isScrolling = false;
		var scrollInterval = null;
		var deleteId = null;

		$(document).ready(function () {
			setTimeout(function () {
				devPopupControlEditSite.SetWidth($(window).width() - 60);
			}, 200);
			$(window).mouseup(function () {
				isDragging = false;
			});
			$(window).mousemove(function (e) {
				if (isDragging) {
					var offset = e.clientY - dragStartY;
					var scrollOffset = $("#siteTreeContainer").scrollTop();
					if (isDragging) {
						var result = scrollOffset + (offset / 10);
						$("#siteTreeContainer").scrollTop(result);
					}
				}
			});
		});

		function saveSite() {
			var form = $("#siteEditForm");
			$(form).submit(function (e) {
				$.ajax({
					type: "POST",
					url: '@Url.Action("EditSite", "Site")',
					data: form.serialize(),
					success: function (response) {
						setTimeout(function () {
							$(".siteEditContainer").remove();
							if (response == "success") {
								devGridViewSite.PerformCallback();
							} else {
								$("body").append(response);
							}
						}, 200);
					}
				});
				e.preventDefault();
			});
			form.submit();
		}

		function saveSiteForAppend() {
			devPopupControlSaveForAppend.Hide();
			var form = $("#siteEditForm");
			$(form).submit(function (e) {
				$.ajax({
					type: "POST",
					url: '@Url.Action("EditSiteForAppend", "Site")',
					data: form.serialize(),
					success: function (response) {
						setTimeout(function () {
							$(".siteEditContainer").remove();
							$("body").append(response);
						}, 200);
					}
				});
				e.preventDefault();
			});
			form.submit();
		}

		function addAppendixToSite(siteId) {
			if (!siteId) return;
			if (siteId == -1) {
				devPopupControlSaveForAppend.Show();
				return;
			}
			$.ajax({
				url: '@Url.Action("AppendAppendixToSite", "Appendix")',
				data: { SiteId: siteId },
				success: function (response) {
					setTimeout(function () {
						$(".deviationEditContainer").remove();
						$(".appendixEditContainer").remove();
						$("body").append(response);
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function addDeviationToSite(siteId) {
			if (!siteId) return;
			$.ajax({
				url: '@Url.Action("AppendDeviationToSite", "Deviation")',
				data: { SiteId: siteId },
				success: function (response) {
					setTimeout(function () {
						$(".deviationEditContainer").remove();
						$(".appendixEditContainer").remove();
						$("body").append(response);
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function addDeviationToAppendix(appendixId) {
			if (!appendixId) return;
			$.ajax({
				url: '@Url.Action("AppendDeviationToAppendix", "Deviation")',
				data: { AppendixId: appendixId },
				success: function (response) {
					setTimeout(function () {
						$(".deviationEditContainer").remove();
						$(".appendixEditContainer").remove();
						$("body").append(response);
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function editDeviation(id) {
			if (!id) return;
			$.ajax({
				url: '@Url.Action("EditDeviation", "Deviation")',
				data: { Id: id },
				success: function (response) {
					setTimeout(function () {
						$(".deviationEditContainer").remove();
						$(".appendixEditContainer").remove();
						$("body").append(response);
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function confirmDeleteDeviation(id) {
			if (!id) return;
			deleteId = id;
			$.ajax({
				type: "GET",
				url: '@Url.Action("GetDeviation", "Deviation")',
				data: { Id: id },
				success: function (response) {
					if (response == "notFound") return;
					var deviation = JSON.parse(response);
					var popupControl = MVCxClientPopupControl.Cast(devPopupControlDeleteDeviation);
					popupControl.SetHeaderText(popupControl.GetHeaderText().replace("{deviation}", deviation.CustomNumber));
					$(".dialogTextDeviation").text($(".dialogTextDeviation").text().replace("{deviation}", deviation.CustomNumber));
					popupControl.Show();
				}
			});
		}

		function deleteDeviation() {
			$.ajax({
				type: "POST",
				url: '@Url.Action("DeleteDeviation", "Deviation")',
				data: { Id: deleteId },
				success: function (response) {
					var popupControl = MVCxClientPopupControl.Cast(devPopupControlDeleteDeviation);
					popupControl.Hide();
					setTimeout(function () {
						devTreeListSiteDeviationAppendices.PerformCallback();
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function assignDeviationToAppendix(id, elem) {
			if (!id || !elem) return;
			$.ajax({
				type: "GET",
				url: '@Url.Action("AssignDeviationToAppendix", "Deviation")',
				data: { Id: id },
				success: function (response) {
					$(".deviationAssignContainer").remove();
					$("body").append(response);
					devPopupControlAssignDeviation.ShowAtElement(elem);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function editAppendix(id) {
			if (!id) return;
			$.ajax({
				url: '@Url.Action("EditAppendix", "Appendix")',
				data: { Id: id },
				success: function (response) {
					setTimeout(function () {
						$(".deviationEditContainer").remove();
						$(".appendixEditContainer").remove();
						$("body").append(response);
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function confirmDeleteAppendix(id) {
			if (!id) return;
			deleteId = id;
			$.ajax({
				type: "GET",
				url: '@Url.Action("GetAppendix", "Appendix")',
				data: { Id: id },
				success: function (response) {
					if (response == "notFound") return;
					var appendix = JSON.parse(response);
					var popupControl = MVCxClientPopupControl.Cast(devPopupControlDeleteAppendix);
					popupControl.SetHeaderText(popupControl.GetHeaderText().replace("{appendix}", appendix.CustomNumber));
					$(".dialogTextAppendix").text($(".dialogTextAppendix").text().replace("{appendix}", appendix.CustomNumber));
					popupControl.Show();
				}
			});
		}

		function deleteAppendix() {
			$.ajax({
				type: "POST",
				url: '@Url.Action("DeleteAppendix", "Appendix")',
				data: { Id: deleteId },
				success: function (response) {
					var popupControl = MVCxClientPopupControl.Cast(devPopupControlDeleteAppendix);
					popupControl.Hide();
					setTimeout(function () {
						devTreeListSiteDeviationAppendices.PerformCallback();
					}, 200);
				},
				error: function () {
					 alert("error occured");
				}
			});
		}

		function startSiteTreeNodeDrag(s, e) {
			if (!s || !e) return;
			if (e.nodeKey[0] == "a") {
				e.cancel = true;
				return;
			}
			dragStartY = e.htmlEvent.clientY;
			isDragging = true;
			var source = e.nodeKey;
		}

		function endSiteTreeNodeDrag(s, e) {
			if (!s || !e) return;
			isDragging = false;
			var sourceKey = e.nodeKey;
			var targetKey = devTreeListSiteDeviationAppendices.GetNodeKeyByRow(e.targetElement);
			if (!sourceKey || !targetKey) return;
			$.ajax({
				type: "POST",
				url: '@Url.Action("AssignDeviationToEntity", "Site")',
				data: { SiteId: @Model.Id, SourceKey: sourceKey, TargetKey: targetKey },
				success: function (response) {
					if (response == "success") {
						setTimeout(function () {
							devTreeListSiteDeviationAppendices.PerformCallback();
						}, 200);
					}
				}
			});
		}

		function onDeviationSaveSuccess() {
			devTreeListSiteDeviationAppendices.PerformCallback();
		}

		function onAppendixSaveSuccess() {
			devTreeListSiteDeviationAppendices.PerformCallback();
		}

		function onListBoxSelectionChanged(s, e) {
			updateText();
		}

		function updateText() {
			var selectedItems = UserValues.GetSelectedItems();
			devDropDownListUserValues.SetText(getSelectedItemsText(selectedItems));
		}

		function synchronizeListBoxValues(s, e) {
			UserValues.UnselectAll();
			var texts = s.GetText().split(textSeparator);
			var values = getValuesByTexts(texts);
			UserValues.SelectValues(values);
			updateText();
		}

		function getSelectedItemsText(items) {
			var texts = [];
			for (var i = 0; i < items.length; i++)
				texts.push(items[i].text);
			return texts.join(textSeparator);
		}

		function getValuesByTexts(texts) {
			var actualValues = [];
			var item;
			for (var i = 0; i < texts.length; i++) {
				item = UserValues.FindItemByText(texts[i]);
				if (item != null)
					actualValues.push(item.value);
			}
			return actualValues;
		}
	</script>

	<style>
		.siteTreeList { }
		.siteTreeList a { text-decoration: none; }
		.siteTreeList a:hover { text-decoration: underline; }
		.siteEditLayoutTable { width: 100%; }
		.siteEditLayoutTable > tbody > tr > td { width: 50%; padding-right: 8px; vertical-align: top }
	</style>

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

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

	s.Modal = true;
	s.Width = new Unit(100, UnitType.Percentage);
	s.CloseAction = CloseAction.CloseButton;
	s.PopupHorizontalAlign = PopupHorizontalAlign.LeftSides;
	s.PopupVerticalAlign = PopupVerticalAlign.TopSides;
	s.PopupHorizontalOffset = 20;
	s.PopupVerticalOffset = 10;
	s.AllowDragging = true;
	s.AllowResize = true;
	s.ShowMaximizeButton = true;
	s.ShowFooter = false;
	s.ShowOnPageLoad = true;
	s.SetContent(() =>
	{
		using (Html.BeginForm("EditSite", "Site", FormMethod.Post, new { id = "siteEditForm" }))
		{
			ViewContext.Writer.Write("<div class='editFormWrapper'>");

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

			ViewContext.Writer.Write("<table class=\"siteEditLayoutTable\"><tbody><tr><td>");
			{
				ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
				{
					ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 30%'>");
					{
						ViewContext.Writer.Write(Html.CustomLabelFor(m => m.CustomNumber, "Kostenstelle:"));
						ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.CustomNumber).ToHtmlString());
						Html.DevExpress().TextBoxFor(m => m.CustomNumber, t =>
						{
							t.Width = new Unit(90, UnitType.Percentage);
						}).Render();
					}
					ViewContext.Writer.Write("</div>");
					ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 70%'>");
					{
						ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Description, "Bauvorhaben:"));
						ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Description).ToHtmlString());
						Html.DevExpress().TextBoxFor(m => m.Description, t =>
						{
							t.Width = new Unit(99, 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: 52%'>");
					{
						ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Start, "Start:"));
						ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Start).ToHtmlString());
						Html.DevExpress().DateEditFor(m => m.Start, t =>
						{
							t.Width = new Unit(95, UnitType.Percentage);
						}).Render();
					}
					ViewContext.Writer.Write("</div>");

					ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 48%'>");
					{
						ViewContext.Writer.Write(Html.CustomLabelFor(m => m.End, "Ende:"));
						Html.DevExpress().DateEditFor(m => m.End, t =>
						{
							t.Width = new Unit(98, UnitType.Percentage);
						}).Render();
					}
					ViewContext.Writer.Write("</div>");
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</td><td>");
			{
				ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
				{
					ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 100%'>");
					{
						ViewContext.Writer.Write(Html.CustomLabelFor(m => m.UserValues, "Benutzer:"));
						ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.UserValues).ToHtmlString());
						Html.DevExpress().DropDownEdit(t =>
						{
							t.Name = "devDropDownListUserValues";
							t.Width = new Unit(100, UnitType.Percentage);
							t.Text = Model.UserDescription;

							t.SetDropDownWindowTemplateContent(l =>
							{
								Html.DevExpress().ListBox(lb =>
								{
									lb.Name = "UserValues";
									lb.Width = new Unit(100, UnitType.Percentage);
									lb.Height = new Unit(250, UnitType.Pixel);
									lb.Properties.TextField = "Description";
									lb.Properties.ValueField = "Id";
									lb.Properties.ValueType = typeof(int);
									lb.Properties.SelectionMode = ListEditSelectionMode.CheckColumn;
									lb.ControlStyle.Border.BorderStyle = BorderStyle.None;
									lb.PreRender = (sender, e) =>
									{
										var listBox = sender as MVCxListBox;

										foreach (ListEditItem listItem in listBox.Items)
										{
											if (Model.UserValues == null || !Model.UserValues.Any(m => m == (int)listItem.Value)) continue;

											listItem.Selected = true;
										}
									};
									lb.Properties.ClientSideEvents.SelectedIndexChanged = "function (s, e) { onListBoxSelectionChanged(s, e); }";
								}).BindList(ViewData["AllUsersWithRole"]).Render();

								t.Properties.ClientSideEvents.TextChanged = "function (s, e) { synchronizeListBoxValues(s, e); }";
								t.Properties.ClientSideEvents.DropDown = "function (s, e) { synchronizeListBoxValues(s, e); }";
							});
						}).Render();
					}
					ViewContext.Writer.Write("</div>");
				}
				ViewContext.Writer.Write("</div>");

				ViewContext.Writer.Write("<div class='inlineModelPropertyContainer'>");
				{
					ViewContext.Writer.Write("<div class='inlineModelProperty' style='width: 100%'>");
					{
						ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Comment, "Kommentar:"));
						ViewContext.Writer.Write(Html.ValidationMessageFor(m => m.Comment).ToHtmlString());
						Html.DevExpress().TextBoxFor(m => m.Comment, t =>
						{
							t.Width = new Unit(100, UnitType.Percentage);
						}).Render();
					}
					ViewContext.Writer.Write("</div>");
				}
				ViewContext.Writer.Write("</div>");
			}
			ViewContext.Writer.Write("</td></tr></tbody></table>");


			ViewContext.Writer.Write(Html.CustomLabelFor(m => m.Deviations, "Vertragsabweichungen / Nachträge:"));

			ViewContext.Writer.Write("<div id=\"siteTreeContainer\" style='width: 100%; overflow: auto; max-height: 450px; border: 1px solid #d0d0d0'>");
			{
				ViewContext.Writer.Write(Html.Partial("~/Views/Sites/_SiteEditTreePartial.cshtml", Model).ToHtmlString());
			}
			ViewContext.Writer.Write("</div>");

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

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

@Html.Partial("~/Views/Shared/_PopupDialogYesNo.cshtml", new GreenTree.Nachtragsmanagement.Web.Models.Global.YesNoDialogModel
{
	PopupName = "devPopupControlSaveForAppend",
	Content = "<div class='dialogTextSaveForAppend' style='padding: 12px'>Damit ein Nachtrag für die Baustelle erfasst werden kann, " +
				"muss Sie zunächst gespeichert werden. Soll die Baustelle jetzt gespeichert werden?</div>",
	HeaderText = "Baustelle speichern",
	YesFunction = "function (s, e) { saveSiteForAppend(); }",
	YesButtonName = "devButtonSaveForAppendYes",
	NoButtonName = "devButtonSaveForAppendNo"
})

@Html.Partial("~/Views/Shared/_PopupDialogYesNo.cshtml", new GreenTree.Nachtragsmanagement.Web.Models.Global.YesNoDialogModel
{
	PopupName = "devPopupControlDeleteAppendix",
	Content = "<div class='dialogTextAppendix' style='padding: 12px'>Sind Sie sicher, dass Sie den Nachtrag \"{appendix}\" und " +
				"alle zugehörigen Vertragsabweichungen löschen möchten? Der Vorgang kann nicht rückgängig gemacht werden.</div>",
	HeaderText = "\"{appendix}\" löschen",
	YesFunction = "function (s, e) { deleteAppendix(); }",
	YesButtonName = "devButtonDeleteAppendixYes",
	NoButtonName = "devButtonDeleteAppendixNo"
})

@Html.Partial("~/Views/Shared/_PopupDialogYesNo.cshtml", new GreenTree.Nachtragsmanagement.Web.Models.Global.YesNoDialogModel
{
	PopupName = "devPopupControlDeleteDeviation",
	Content = "<div class='dialogTextDeviation' style='padding: 12px'>Sind Sie sicher, dass Sie die Vertragsabweichung \"{deviation}\" " +
				"löschen möchten? Der Vorgang kann nicht rückgängig gemacht werden.</div>",
	HeaderText = "\"{deviation}\" löschen",
	YesFunction = "function (s, e) { deleteDeviation(); }",
	YesButtonName = "devButtonDeleteDeviationYes",
	NoButtonName = "devButtonDeleteDeviationNo"
})

</div>