(function () {
	'use strict';

	if (!window.AVINTracker || !window.AVINTracker.url || !window.AVINTracker.nonce || !window.AVINTracker.type) {
		return;
	}

	var heartbeatTimer = null;
	var heartbeatInterval = Math.max(30000, Number(window.AVINTracker.heartbeatInterval) || 45000);

	function payload(action) {
		var data = new FormData();
		data.append('action', action);
		data.append('nonce', window.AVINTracker.nonce);
		data.append('object_id', window.AVINTracker.id || 0);
		data.append('object_type', window.AVINTracker.type);
		data.append('page_title', window.AVINTracker.title || document.title || '');
		data.append('page_url', window.AVINTracker.pageUrl || window.location.href);
		return data;
	}

	function post(action) {
		var data = payload(action);

		if (navigator.sendBeacon) {
			navigator.sendBeacon(window.AVINTracker.url, data);
			return;
		}

		fetch(window.AVINTracker.url, {
			method: 'POST',
			body: data,
			credentials: 'same-origin',
			keepalive: true,
			cache: 'no-store'
		}).catch(function () {});
	}

	function refreshPresence() {
		if (document.visibilityState && document.visibilityState !== 'visible') {
			return;
		}

		post('avin_refresh_presence');
	}

	post('avin_track_view');

	heartbeatTimer = window.setInterval(refreshPresence, heartbeatInterval);
	document.addEventListener('visibilitychange', function () {
		if (document.visibilityState === 'visible') {
			refreshPresence();
		}
	});
	window.addEventListener('pagehide', function () {
		if (heartbeatTimer) {
			window.clearInterval(heartbeatTimer);
		}
	});
}());
