/**
 * This function return instance of CEM-object
 *
 * @return CEMClass-instance
 */
var CEM = undefined;
function CEMClass() {
	var URL = undefined;
	var SPARAMS = {};
	var CUR = undefined;
	var C = undefined;
	var T = '168cd28135675b';
	var S = '';
	var inArray = function(needle, array) {
		for (var i = 0; i < array.length; ++i) {
			if (array[i] == needle) {
				return true;
			}
		}
		return false;
	};
	var makeList = function(to, from) {
		for (var i in from) {
			if (typeof to[i] === typeof []) {
				to[i].push(from[i]);
			} else if (typeof to[i] !== 'undefined') {
				to[i] = [to[i], from[i]];
			} else {
				to[i] = from[i];
			}
		}
		return to;
	};
	var inSecretList = function(e) {
		if (typeof e === undefined) {
			return false;
		}
		if (inArray(e.name, ['file', 'password'])) {
			return false;
		}
		if (typeof e.type !== 'undefined' && inArray(e.type, ['file', 'password'])) {
			return false;
		}
		return true;
	};
	var checkElement = function(e) {
		if (e.length <= 0) {
			return {};
		}
		var ret = {}, i = 0;
		for (i; i < e.length; ++i) {
			v = e[i];
			if (typeof v.name === 'undefined') {
				continue;
			}
			if (typeof v.value !== typeof '' || v.value.length <= 0) {
				continue;
			}
			if (! inSecretList(v)) {
				continue;
			}
			var n = {};
			if (typeof v.type !== 'undefined' && v.type.toLowerCase() == 'checkbox') {
				if (typeof v.checked !== 'undefined' && v.checked) {
					n[v.name] = v.value;
				}
			} else {
				n[v.name] = v.value;
			}
			ret = makeList(ret, n);
		}
		return ret;
	};

	var elementSend = function(e, c) {
		if (! e.target || e.target.nodeName.toLowerCase() != 'form') {
			return;
		}
		var a = checkElement(e.target.getElementsByTagName('input'));
		a = makeList(a, checkElement(e.target.getElementsByTagName('select')));
		CEM.send('pbr', a, c);
	};

	/**
	 * Inject forms injects cem token/channel in all the forms at the page.
	 *
	 * Input name can be overriden by declaring data-cem-token-input-name or
	 * data-cem-channel-input-name attributes for form element.
	 *
	 */
	var injectForms = function() {
		var fs = document.getElementsByTagName('form');
		var tmp = undefined, i = 0;

		for (i; i < fs.length; ++i) {
			if (typeof fs[i].getAttribute === 'undefined') {
				continue;
			}

			var cem_token_input_name = undefined;
			if (fs[i].hasAttribute('data-cem-token-input-name')) {
				cem_token_input_name = fs[i].getAttribute('data-cem-token-input-name');
			} else {
				cem_token_input_name = 'cem_token';
			}

			if (typeof cem_token_input_name !== 'undefined' && cem_token_input_name != null) {
				var e = document.createElement('input');
				e.setAttribute('type', 'hidden');
				e.setAttribute('name', cem_token_input_name);
				e.setAttribute('value', T);
				fs[i].appendChild(e);
			}

			var cem_channel_input_name = undefined;
			if (fs[i].hasAttribute('data-cem-channel-input-name')) {
				cem_channel_input_name = fs[i].getAttribute('data-cem-channel-input-name');
			} else {
				cem_channel_input_name = 'cem_channel';
			}

			if (typeof cem_channel_input_name !== 'undefined' && cem_channel_input_name != null) {
				var e = document.createElement('input');
				e.setAttribute('type', 'hidden');
				e.setAttribute('name', cem_channel_input_name);
				e.setAttribute('value', 'cem,' + C);
				fs[i].appendChild(e);
			}
		}
	};
	var injectSubmit = function() {
		var body = document.getElementsByTagName('body');
		if (body.length <= 0) {
			return;
		}
		body = body[0];
		body.addEventListener("submit", elementSend);
	};
	var onLoad = function(f) {
		var ol = window.onload;
		if (typeof window.onload !== 'function') {
			window.onload = f;
		} else {
			window.onload = function() {
				if (ol) {
					ol();
				}
				f();
			};
		}
	};
	var href = undefined;
	var listenUrl = function() {
		if (typeof href === 'undefined') {
			href = window.location.href;
		}
		setTimeout(function() {
			if (href != window.location.href) {
				href = window.location.href;
				var s = { 'ajax': true };
				if (window.location.hash.length > 0) {
					s.hash = window.location.hash;
				}
				CEM.send('pbr', s);
			}
			listenUrl();
		}, 1000);
	};
	var listenBrowsingTime = function() {
		setTimeout(function() {
			var s = { 'ajax': true, bt: 30 };
			if (window.location.hash.length > 0) {
				s.hash = window.location.hash;
			}
			CEM.send('pbr', s);
		}, 30000);
	};
	var loadList = [];
	var staticParams = function(p) {
		for (var i in SPARAMS) {
			p[i] = SPARAMS[i];
		}
		return p;
	};
	var Interface = function() {
		this.setStaticParam = function(key, value) {
			if (key === 'liana_t') {
				return;
			}
			SPARAMS[key] = value;
		};
		this.setUrl = function(url, nosend) {
			URL = url;
			var c = URL.match(/\/t\/([^\/]+)\/js/);
			if (c) {
				C = c[1];
			}
			var t = T.match(/^t=([\w\d]+)$/);
			if (t) {
				T = t[1];
			}
			var d = new Date();
			var secure = '';
			var sameSite = 'SameSite=Lax';
			d.setDate(d.getDate() + 365);
			if (location.protocol === 'https:') {
				secure = '; Secure';
				sameSite = 'SameSite=None';
			}
			document.cookie = 'liana_t=' + T + '; Expires=' + d.toUTCString() + '; ' + sameSite  + '; Path=/' + secure;
			document.cookie = 'liana_s=' + S + '; Expires=' + d.toUTCString() + '; ' + sameSite  + '; Path=/' + secure;
			SPARAMS['liana_t'] = T;
			if (nosend) {
				return this;
			}
			var me = this;
			onLoad(function() {
				if (document.readyState === "complete") {
					me.manualLoad();
				}
			});
			listenUrl();
			listenBrowsingTime();
			return this;
		};
		this.injectForms = function() {
			loadList.push(injectForms);
			return this;
		};
		this.injectSubmit = function(form) {
			loadList.push(injectSubmit);
			return this;
		};
		this.manualLoad = function() {
			for (var i = 0; i < loadList.length; ++i) {
				loadList[i]();
			}
			loadList = [];
		};
		this.sendForm = function(form, c) {
			form.nodeName = 'form';
			elementSend({
				'target': form,
				'complete': c
			});
		};
		this.getToken = function() {
			return T;
		};
		this.send = function(v, p, c, url) {
			if (typeof URL === 'undefined') {
				return;
			}
			p = staticParams(p);
			var sp = "", value = "";
			for (var i in p) {
				if (i.match(/^cem_/)) {
					continue;
				}
				if (typeof p[i] === typeof []) {
					for (var m in p[i]) {
						sp += encodeURIComponent(i) + "[]=" + encodeURIComponent(p[i][m]) + "&";
					}
				} else {
					sp += encodeURIComponent(i) + "=" + encodeURIComponent(p[i]) + "&";
				}
			}
			if (sp.length <= 3) {
				return;
			}
			var origin = window.location.origin + window.location.pathname;
			if (typeof origin !== 'undefined' && ! sp.match(/href=/)) {
				sp += 'href=' + encodeURIComponent(origin);
			}
			var xmlHttp = new XMLHttpRequest();
			xmlHttp.onloadend = c;
			var u = typeof url === 'undefined' ? URL : url;
			if (u.indexOf("?") !== -1) {
				u += "&";
			} else {
				u += "?";
			}
			u += 'v=' + encodeURIComponent(v) + '&' + sp;
			var urlParams = new URLSearchParams(window.location.search);
			if (urlParams.has('liana_pv') && urlParams.get('liana_pv').match('^[a-z0-9]{32}$') && ! sp.match(/uid=/)) {
				u += '&uid=' + encodeURIComponent(urlParams.get('liana_pv'));
			}
			xmlHttp.withCredentials = true;
			xmlHttp.open("GET", u, true);
			xmlHttp.send(null);
			return CEM;
		};
	};
	if (typeof CEM === 'undefined') {
		CEM = new Interface();
	}
	return CEM;
}
