/**
 * Kantan Analytics — form session field injector.
 *
 * Adds hidden kantan_session_id / kantan_visitor_id inputs to every form on the
 * page so form-plugin submissions can be attributed to the visitor's session.
 * IDs come from the tracking script's sessionStorage/localStorage; if neither is
 * present (e.g. logged-in admins, who aren't tracked) the script no-ops.
 */
(function () {
	function injectFields(form, name, value) {
		if (!value || form.querySelector('input[name="' + name + '"]')) {
			return;
		}
		var input = document.createElement('input');
		input.type = 'hidden';
		input.name = name;
		input.value = value;
		form.appendChild(input);
	}

	function injectSessionFields() {
		var sessionId = sessionStorage.getItem('kantan_session_id');
		var visitorId = localStorage.getItem('kantan_visitor_id');
		if (!sessionId && !visitorId) {
			return;
		}

		var forms = document.querySelectorAll('form');
		for (var i = 0; i < forms.length; i++) {
			injectFields(forms[i], 'kantan_session_id', sessionId);
			injectFields(forms[i], 'kantan_visitor_id', visitorId);
		}
	}

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

	// Re-inject every 2 seconds to catch AJAX-loaded forms.
	setInterval(injectSessionFields, 2000);
})();
