<%--
/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * Subscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */
--%>

<liferay-util:html-top>
	<link href="<%= PortalUtil.getStaticResourceURL(request, application.getContextPath() + "/css/form_navigator.css") %>" rel="stylesheet" type="text/css" />
</liferay-util:html-top>

<div class="taglib-form-navigator" id="<portlet:namespace />tabsBoundingBox">
	<aui:input name="modifiedSections" type="hidden" />

	<div class="form-steps" id="<portlet:namespace />tabs">
		<liferay-util:buffer
			var="formNavigatorBottom"
		>
			<c:if test="<%= formNavigatorStepsDisplayContext.isShowButtons() %>">
				<aui:button-row>
					<aui:button primary="<%= true %>" type="submit" />

					<aui:button href="<%= formNavigatorStepsDisplayContext.getBackURL() %>" type="cancel" />
				</aui:button-row>
			</c:if>

			<%= Validator.isNotNull(formNavigatorStepsDisplayContext.getHtmlBottom()) ? formNavigatorStepsDisplayContext.getHtmlBottom() : StringPool.BLANK %>
		</liferay-util:buffer>

		<liferay-util:buffer
			var="formSectionsBuffer"
		>
			<div class="form-navigator-content">

				<%
				for (FormNavigatorEntry<Object> formNavigatorEntry : formNavigatorEntries) {
					String sectionId = namespace + formNavigatorStepsDisplayContext.getSectionId(formNavigatorEntry.getKey());
				%>

					<!-- Begin fragment <%= sectionId %> -->

					<div class="form-section <%= (curSection.equals(formNavigatorEntry.getKey()) || curSection.equals(sectionId)) ? "active" : StringPool.BLANK %>" id="<%= sectionId %>">

						<%
						PortalIncludeUtil.include(pageContext, formNavigatorEntry::include);
						%>

					</div>

					<!-- End fragment <%= sectionId %> -->

				<%
				}
				%>

			</div>
		</liferay-util:buffer>

		<ul class="form-navigator multi-step-progress-bar">
			<%= Validator.isNotNull(formNavigatorStepsDisplayContext.getHtmlTop()) ? formNavigatorStepsDisplayContext.getHtmlTop() : StringPool.BLANK %>

			<%
			String[] modifiedSections = StringUtil.split(ParamUtil.getString(request, "modifiedSections"));

			String errorSection = (String)request.getAttribute(WebKeys.ERROR_SECTION);

			if (Validator.isNull(errorSection)) {
				modifiedSections = null;
			}

			boolean error = false;

			for (int i = 0; i < categoryLabels.length; i++) {
				String category = categoryLabels[i];
				String[] sectionKeys = categorySectionKeys[i];
				String[] sectionLabels = categorySectionLabels[i];
			%>

				<c:if test="<%= sectionKeys.length > 0 %>">
					<c:if test="<%= Validator.isNotNull(category) %>">
						<li class="list-group-item nav-header"><liferay-ui:message key="<%= category %>" /></li>
					</c:if>

					<%
					if (Validator.isNotNull(errorSection)) {
						curSection = StringPool.BLANK;

						error = true;
					}

					int step = 1;
					boolean isFoundActiveStep = false;

					for (int j = 0; j < sectionKeys.length; j++) {
						String sectionIcon = "live";
						String sectionKey = sectionKeys[j];
						String sectionLabel = sectionLabels[j];

						String sectionId = namespace + formNavigatorStepsDisplayContext.getSectionId(sectionKey);

						Boolean show = (Boolean)request.getAttribute(WebKeys.FORM_NAVIGATOR_SECTION_SHOW + sectionId);

						if ((show != null) && !show) {
							continue;
						}

						String cssClass = StringPool.BLANK;

						if (sectionId.equals(namespace + errorSection)) {
							cssClass += " section-error";

							curSection = sectionKey;
						}

						if (curSection.equals(sectionKey) || curSection.equals(sectionId)) {
							cssClass += " active";
							isFoundActiveStep = true;
							sectionIcon = "circle";
						}

						if (!isFoundActiveStep) {
							cssClass += " complete";
							sectionIcon = "check";
						}

						if (ArrayUtil.contains(modifiedSections, sectionId)) {
							cssClass += " section-modified";
						}
					%>

						<li class="<%= cssClass %>" data-sectionId="<%= sectionId %>" id="<%= sectionId %>Tab">
							<div class="progress-bar-title"><%= sectionLabel %></div>

							<div class="divider">
								<svg aria-hidden="true" class="lexicon-icon lexicon-icon-<%= sectionIcon %>">
									<use xlink:href="<%= FrontendIconsUtil.getSpritemap(themeDisplay) %>#<%= sectionIcon %>"></use>
								</svg>
							</div>

							<div class="progress-bar-step"><liferay-ui:message key="<%= String.valueOf(step) %>" /></div>
						</li>

					<%
						step++;
					}
					%>

				</c:if>

			<%
			}
			%>

		</ul>

		<%= formSectionsBuffer %>

		<%= formNavigatorBottom %>
	</div>
</div>

<aui:script use="anim,aui-event-input,aui-tabview,aui-url,history,io-form,scrollview">
	var formNode = A.one(
		'#<portlet:namespace /><%= formNavigatorStepsDisplayContext.getFormName() %>'
	);

	Liferay.component(
		'<portlet:namespace /><%= formNavigatorStepsDisplayContext.getFormName() %>Tabview',
		() => {
			return new A.TabView({
				boundingBox: '#<portlet:namespace />tabsBoundingBox',
				srcNode: '#<portlet:namespace />tabs',
				type: 'list',
			}).render();
		}
	);

	var tabview = Liferay.component(
		'<portlet:namespace /><%= formNavigatorStepsDisplayContext.getFormName() %>Tabview'
	);

	var listNode = tabview.get('listNode');

	var scrollAnim = new A.Anim({
		duration: 0.3,
		node: listNode,
		to: {
			scrollLeft: function () {
				var activeTabNode = tabview.getActiveTab();

				var scrollLeft = listNode.get('scrollLeft');

				return activeTabNode.getX() + scrollLeft - listNode.getX();
			},
		},
	});

	function selectTabBySectionId(sectionId) {
		var instance = this;

		var tabNode = A.one('#' + sectionId + 'Tab');

		var tab = A.Widget.getByNode(tabNode);

		var tabIndex = tabview.indexOf(tab);

		if (tab && tabIndex > -1) {
			tabview.selectChild(tabIndex);
		}

		updateRedirectForSectionId(sectionId);

		var listNodeRegion = listNode.get('region');

		if (tabNode && !tabNode.inRegion(listNodeRegion, true)) {
			scrollAnim.run();
		}

		Liferay.fire('formNavigator:reveal' + sectionId);
	}

	function updateSectionError() {
		var tabNode = tabview.get('selection').get('boundingBox');

		var sectionId = tabNode.getData('sectionId');

		tabNode.toggleClass(
			'section-error',
			A.one('#' + sectionId).one('.error-field')
		);
	}

	function updateSectionStatus() {
		var tabNode = tabview.get('selection').get('boundingBox');

		var sectionId = tabNode.getData('sectionId');

		var modifiedSectionsNode = A.one('#<portlet:namespace />modifiedSections');

		var modifiedSections = modifiedSectionsNode.val().split(',');

		modifiedSections.push(sectionId);
		modifiedSections = A.Array.dedupe(modifiedSections);
		modifiedSectionsNode.val(modifiedSections.join());

		tabNode.addClass('section-modified');
	}

	function updateRedirectForSectionId(sectionId) {
		var redirect = A.one('#<portlet:namespace />redirect');

		if (redirect) {
			const url = new URL(
				redirect.val() ||
					'<%= formNavigatorStepsDisplayContext.getPortletURL() %>'
			);

			url.hash = '';
			url.searchParams.set('<portlet:namespace />historyKey', sectionId);

			redirect.val(url.toString());
		}
	}

	var history = new A.HistoryHash();

	tabview.after('selectionChange', (event) => {
		var tab = event.newVal;

		var tabIndex = tabview.indexOf(tab);

		tabview.each((item, index) => {
			var node = tabview.item(index).get('boundingBox');

			if (tabview.indexOf(item) < tabIndex) {
				node.addClass('complete');
				node.one('.divider').setHTML(
					Liferay.Util.getLexiconIconTpl('check')
				);
			}
			else if (tabview.indexOf(item) === tabIndex) {
				node.one('.divider').setHTML(
					Liferay.Util.getLexiconIconTpl('circle')
				);
			}
			else {
				node.one('.divider').setHTML(
					Liferay.Util.getLexiconIconTpl('live')
				);
			}
		});

		var boundingBox = tab.get('boundingBox');

		var sectionId = boundingBox.getData('sectionId');

		history.addValue('<portlet:namespace />tab', sectionId);
	});

	A.on('history:change', (event) => {
		var state = event.newVal;

		var changed = event.changed.<portlet:namespace />tab;

		var removed = event.removed.<portlet:namespace />tab;

		if (
			event.src === A.HistoryHash.SRC_HASH ||
			event.src === A.HistoryBase.SRC_ADD
		) {
			if (changed) {
				selectTabBySectionId(changed.newVal);
			}
			else if (removed) {
				tabview.selectChild(0);
			}
			else if (state) {
				var sectionId = state.<portlet:namespace />tab;

				if (!sectionId) {
					sectionId = '<portlet:namespace />' + state.tab;
				}

				selectTabBySectionId(sectionId);
			}
		}
	});

	if (<%= error %>) {
		history.addValue(
			'<portlet:namespace />tab',
			'<portlet:namespace /><%= errorSection %>'
		);
	}
	else {
		const currentUrl = new URL(location.href);

		let currentAnchor;

		if (currentUrl.hash) {
			currentAnchor = currentUrl.hash.substring(1);
		}
		else {
			currentAnchor = currentUrl.searchParams.get(
				'<portlet:namespace />historyKey'
			);
		}

		if (currentAnchor) {
			var locationSectionId = currentAnchor.substring(
				currentAnchor.indexOf('=') + 1
			);

			if (locationSectionId.indexOf('<portlet:namespace />') === -1) {
				locationSectionId = '<portlet:namespace />' + locationSectionId;
			}

			selectTabBySectionId(locationSectionId);
		}
	}

	if (formNode) {

		<%
		String focusField = (String)request.getAttribute("liferay-ui:error:focusField");
		%>

		var focusField;

		<c:choose>
			<c:when test="<%= Validator.isNotNull(focusField) %>">
				focusField = formNode.one('#<portlet:namespace /><%= focusField %>');
			</c:when>
			<c:otherwise>
				focusField = formNode.one(
					'.form-section.active input:not([type="hidden"]).field'
				);
			</c:otherwise>
		</c:choose>

		if (focusField) {
			Liferay.Util.focusFormField(focusField);
		}

		formNode.all('.modify-link').on('click', updateSectionStatus);

		formNode.delegate('change', updateSectionStatus, 'input, select, textarea');

		formNode.on('blur', updateSectionError, 'input, select, textarea');

		formNode.on('autofields:update', updateSectionError);

		var updateSectionOnError = function (event) {
			var form = event.form;

			if (form.formNode.compareTo(formNode)) {
				var validator = form.formValidator;

				validator.on('submitError', () => {
					var errorClass = validator.get('errorClass');

					var errorField = formNode.one('.' + errorClass);

					if (errorField) {
						var errorSection = errorField.ancestor('.form-section');

						var errorSectionId = errorSection.attr('id');

						selectTabBySectionId(errorSectionId);

						updateSectionError();
					}
				});
			}
		};

		var detachUpdateSection = function (event) {
			if (event.portletId === '<%= portletDisplay.getRootPortletId() %>') {
				Liferay.detach('form:registered', updateSectionOnError);

				Liferay.detach('destroyPortlet', detachUpdateSection);
			}
		};

		Liferay.after('form:registered', updateSectionOnError);

		Liferay.on('destroyPortlet', detachUpdateSection);
	}
</aui:script>