(function() {
	var rootId = 'sitefort-admin-app';
	var hiddenClass = 'sitefort-admin-notice-hidden';
	var noticeSelector = [
		'.notice',
		'.updated',
		'.error',
		'.update-nag',
		'.fs-notice',
		'#message',
		'[class*="notice-"]'
	].join(',');

	function isElement(value) {
		return value && value.nodeType === 1;
	}

	function isInsideSiteFortApp(node) {
		return !!(isElement(node) && node.closest('#' + rootId));
	}

	function isInsideScreenMeta(node) {
		return !!(isElement(node) && node.closest('#screen-meta, #screen-meta-links'));
	}

	function isSuppressibleNotice(node) {
		if (!isElement(node)) {
			return false;
		}

		if (node.id === rootId || isInsideSiteFortApp(node) || isInsideScreenMeta(node)) {
			return false;
		}

		if (node.closest && node.closest('.sitefort-compatibility-notice')) {
			return false;
		}

		if (!node.closest('#wpbody-content')) {
			return false;
		}

		return node.matches(noticeSelector);
	}

	function hideNotice(node) {
		if (!isSuppressibleNotice(node)) {
			return;
		}

		node.classList.add(hiddenClass);
		node.setAttribute('data-sitefort-hidden-notice', '1');
		node.style.display = 'none';
	}

	function scan(container) {
		if (!isElement(container) && container !== document) {
			return;
		}

		var root = container === document ? document.getElementById('wpbody-content') : container;
		if (!root) {
			return;
		}

		if (isSuppressibleNotice(root)) {
			hideNotice(root);
		}

		var notices = root.querySelectorAll(noticeSelector);
		notices.forEach(hideNotice);
	}

	function boot() {
		scan(document);

		var target = document.getElementById('wpbody-content');
		if (!target || typeof MutationObserver === 'undefined') {
			return;
		}

		var observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				mutation.addedNodes.forEach(function(node) {
					if (!isElement(node)) {
						return;
					}

					hideNotice(node);
					scan(node);
				});
			});
		});

		observer.observe(target, { childList: true, subtree: true });
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', boot);
	} else {
		boot();
	}
}());
