/*
	Created by Michael Schuijff <michael@reglobe.nl>
	Copyright Lost Images, The Netherlands
	
	For more information, visit www.michaelschuijff.nl
*/

window.dataLayer = window.dataLayer || [];

var analytics = new function () {
	let analytics = this;
	
	analytics.init = function (currentView) {
		if (config.offline || !(window.cordova || location.protocol == 'https:')) {
			return;
		}

		if (options.get('cookies') != 'accepted') {
			return;
		}
		
		loadScript('https://www.googletagmanager.com/gtag/js?id=' + config.analytics);
		
		analytics.push('js', new Date());
		analytics.push('config', config.analytics, { send_page_view: false });
		
		if (currentView) {
			analytics.page();
		}
	}
	
	analytics.page = function () {
		let details = {
			page_title: config.name, page_location: config.url + router.getURL(), language: navigator.language, page_encoding: 'UTF-8'
		};
		
		if (window.activeView) {
			details.page_title = activeView.getTitle() || details.page_title;
		}
		
		analytics.push('event', 'page_view', details);
	}
	
	analytics.push = function () {
		if (config.offline || !(window.cordova || location.protocol == 'https:')) {
			return;
		}

		if (options.get('cookies') != 'accepted') {
			return;
		}
		
		dataLayer.push(arguments);
	}
}

document.addEventListener('loaded', () => {
	if (config.bot) {
		return;
	}
	
	analytics.init();

	let consent = options.get('cookies');
	
	if (consent == 'accepted' || (!!+consent && Date.now() < +consent * 1000)) {
		return;
	}
	
	let container = createElement('div', 'consent', createElement('h2', 'uppercase', __('We value your privacy')));
	
	let text;
	
	if (window.cordova) {
		text = __('This app uses cookies to analyze our traffic.');
	} else {
		text = __('This website uses cookies to analyze our traffic.');
	}
	
	text += ' ' + __("By clicking 'Accept' you consent to our use of cookies.");
		
	container.append(createElement('p', null, text));
	
	let link = createElement('a', null, __('Privacy policy'));
	link.href = '/privacy-policy';
	
	container.append(createElement('p', null, link));
	
	let buttons = createElement('div', 'buttons');
	
	buttons.onclick = (e) => {
		if (e.target.matches('button')) {
			container.remove();
		}
	}
	
	{
		let button = createElement('button', 'button uppercase button-accept', __('Accept'));
		
		button.onclick = () => {
			options.set('cookies', 'accepted');
			analytics.init(true);
		}
		
		buttons.append(button);
	}
	
	{
		let button = createElement('button', 'button uppercase button-reject', __('Reject'));
		
		button.onclick = () => {
			options.set('cookies', (Date.now() / 1000 | 0) + 3600);
		}
		
		buttons.append(button);
	}
	
	container.append(buttons);
	
	document.body.append(container);
});
