var ac_timer = 0;

function autocomplete(inp) {
	var currentFocus;

	inp.addEventListener("input", function(e) {
		var a, b, i, val = this.value, me = this;

		closeAllLists();

		if (!val || val.length < 2) {
			return false;
		}

	    if (ac_timer) {
	        clearTimeout(ac_timer);
	    }

		ac_timer = setTimeout(function() {
			currentFocus = -1;

			a = document.createElement("DIV");
			a.setAttribute("id", me.id + "autocomplete-list");
			a.setAttribute("class", "autocomplete-items");

			me.parentNode.appendChild(a);

			addSuggestions(a, val);
		}, 500);
	});

	inp.addEventListener("keydown", function(e) {
		var x = document.getElementById(this.id + "autocomplete-list");

		if (x) {
			x = x.getElementsByTagName("div");
		}

		if (e.keyCode == 40) { // Ned
			currentFocus++;
			addActive(x);
		}
		else if (e.keyCode == 38) { // Op
			currentFocus--;
			addActive(x);
		}
		else if (e.keyCode == 13) { // Enter
			e.preventDefault();
			if (currentFocus > -1 && x) {
				x[currentFocus].click();
			}
			else {
				inp.form.submit();
			}
		}
	});

	document.addEventListener("click", function (e) {
		closeAllLists(e.target);
	});

	function addSuggestions(a, val) {
		if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		}
		else {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}

		xmlhttp.onreadystatechange = function() {
			if (this.readyState == 4 && this.status == 200) {
				var arr = JSON.parse(this.responseText);

				for (i = 0; i < arr.length; i++) {
					b = document.createElement("DIV");
					b.classList.add(arr[i].type);

					b.innerHTML = '';
					b.innerHTML += '<img src="' + arr[i].thumbnail + '">';
					b.innerHTML += arr[i].name;

					if (arr[i].product_cnt) {
						b.innerHTML += ' (' + arr[i].product_cnt + ')';
					}

					if (arr[i].price) {
						var price = arr[i].price;
						price_formatted = new Intl.NumberFormat('da', {"minimumFractionDigits": 2}).format(price);

						b.innerHTML += ' <span class="price"">' + price_formatted + ' ' + arr[i].currency + '</span>';
					}

					b.innerHTML += "<input type='hidden' name='str' value='" + arr[i].name + "'>";
					if (arr[i].url) {
						b.innerHTML += "<input type='hidden' name='url' value='" + arr[i].url + "'>";
					}

					b.addEventListener("click", function(e) {
						var inputs = this.getElementsByTagName("input")

						inp.value = inputs[0].value;
						closeAllLists();

						if (inputs[1]) {
							top.location = inputs[1].value;
						}
						else {
							inp.form.submit();
						}

					});

					a.appendChild(b);
				}

				b = document.createElement("DIV");
				b.classList.add('search');

				b.innerHTML = '<strong>Søg efter:</strong> ' + val;
				b.innerHTML += "<input type='hidden' name='str' value='" + val + "'>";

				b.addEventListener("click", function(e) {
					inp.value = this.getElementsByTagName("input")[0].value;
					closeAllLists();
					inp.form.submit();
				});

				a.appendChild(b);
			}
		}

		xmlhttp.open("GET", "ajax_search?term=" + val + "&include=products,categories,landing_pages,pages", true);
		xmlhttp.send();
	}

	function addActive(x) {
		if (!x) {
			return false;
		}

		removeActive(x);

		if (currentFocus >= x.length) {
			currentFocus = 0;
		}

		if (currentFocus < 0) {
			currentFocus = x.length - 1;
		}

		x[currentFocus].classList.add("autocomplete-active");
	}

	function removeActive(x) {
		for (var i = 0; i < x.length; i++) {
			x[i].classList.remove("autocomplete-active");
		}
	}

	function closeAllLists(elmnt) {
		var x = document.getElementsByClassName("autocomplete-items");
		for (var i = 0; i < x.length; i++) {
			if (elmnt != x[i] && elmnt != inp) {
				x[i].parentNode.removeChild(x[i]);
			}
		}
	}
}

autocomplete(document.getElementById("top-search"));