document.addEventListener('DOMContentLoaded', function() { history.pushState( {}, document.title, location.href ); window.addEventListener( 'popstate', function( event ){ location.reload(); }); const paramsToTrack = [ 'Src', 'fbclid', 'gclid' ]; paramsToTrack.forEach( paramName => { const paramValue = getSrcQueryParam(paramName); if (paramValue) { setCookie( '_tbv_' + paramName, paramValue, 90); setCookie( '_tbt_' + paramName, new Date().toISOString(), 90); } }); console.log( 'Debugging mode:', debugging_mode ); const canonicals = document.querySelectorAll('link[rel="canonical"]'); canonicals.forEach(el => el.remove()); let metaDescription = document.querySelector('meta[name="description"]'); if (!metaDescription) { metaDescription = document.createElement('meta'); metaDescription.setAttribute('name', 'description'); document.head.appendChild(metaDescription); } metaDescription.setAttribute('content', 'TreBeste.no'); const inputQuery = document.getElementById("form-field-query"); const inputZip = document.getElementById("form-field-zipcode"); const submitBtn = document.getElementById("form-button-search"); const suggestionDropdown = document.getElementById("dynamic_suggestions_dropdown"); let activeIndex = -1; // Autofyll og start søk fra URL const params = new URLSearchParams(window.location.search); const query = params.get("finn"); const zip = params.get("postnr"); if (query && zip) { if (inputQuery && inputZip && submitBtn) { inputQuery.value = query; inputZip.value = zip; setTimeout(() => submitBtn.click(), 200); } } else { const path = window.location.pathname; const pathParts = path.split('/').filter(p => p); if ( pathParts[0] && pathParts[0].match( /^leverand/ ) && pathParts.length >= 3) { const queryFromPath = decodeURIComponent(pathParts[1].replace(/_.+/, '')); /* const queryFromPath = pathParts[1].replace( /_.+/, '' ); */ const zipFromPath = pathParts[2].replace('postnr_', ''); if (inputQuery && inputZip && submitBtn) { inputQuery.value = queryFromPath; inputZip.value = zipFromPath; setTimeout(() => submitBtn.click(), 200); } } else if (path === '/') { const savedQuery = getCookie("last_query"); const savedZip = getCookie("last_zip"); if (savedZip) inputZip.value = savedZip; inputZip.style.marginTop = '6px'; submitBtn.style.marginTop = '8px'; if ( window.location.hash == '' ) { inputQuery?.focus(); } } } // Sett opp faste forslag én gang under query-feltet const wrapper = document.querySelector('.elementor-field-group-query'); let dynamicSuggestionBox = null; let dynamicSuggestionIconBox = null; if (wrapper && inputQuery && inputZip) { dynamicSuggestionBox = document.createElement('div'); dynamicSuggestionBox.id = "suggestion_wrapper"; dynamicSuggestionBox.style.display = 'none'; const options = [ "Snekker", "Elektriker", "Eiendomsmegler", "Advokat", "Hjemmelader", "Rørlegger", "Maler", "Varmepumpe" ]; for (let i = options.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [options[i], options[j]] = [options[j], options[i]]; } dynamicSuggestionBox.innerHTML = options.map(txt => `${txt}`).join(''); dynamicSuggestionBox.style.overflow = 'hidden'; wrapper.appendChild(dynamicSuggestionBox); // Ikonbaserte forslag dynamicSuggestionIconBox = document.createElement('div'); dynamicSuggestionIconBox.id = "suggestion_icon_wrapper"; dynamicSuggestionIconBox.style.marginTop = '8px'; dynamicSuggestionIconBox.style.display = 'block'; dynamicSuggestionIconBox.style.margin = '8px 10px 0 10px'; dynamicSuggestionIconBox.style.textAlign = 'center'; dynamicSuggestionIconBox.style.height = '54px'; dynamicSuggestionIconBox.style.overflow = 'hidden'; dynamicSuggestionIconBox.style.fontSize = '14px'; function toFilename(txt) { return txt .toLowerCase() .replace(/ø/g, 'oe') .replace(/å/g, 'aa') .replace(/æ/g, 'ae') .replace(/[^a-z0-9]+/g, '_') .replace(/^_|_$/g, ''); } options.forEach(txt => { const span = document.createElement('span'); span.className = 'query_option'; span.style.cursor = 'pointer'; span.style.display = 'inline-block'; span.style.textAlign = 'center'; span.style.padding = '0 6px 0 6px'; const img = document.createElement('img'); img.src = '/imgs/icon-' + toFilename(txt) + '.png'; img.height = 32; img.style.display = 'block'; img.style.margin = '0 auto 4px'; const label = document.createElement('div'); label.innerHTML = txt; span.appendChild(img); span.appendChild(label); dynamicSuggestionIconBox.appendChild(span); }); wrapper.appendChild(dynamicSuggestionIconBox); wrapper.querySelectorAll('.query_option').forEach(el => { el.addEventListener('click', () => { const selected = el.textContent.trim(); inputQuery.value = selected; const zipValue = inputZip.value.trim(); if (zipValue !== '') { handleQuery(selected, zipValue); } else if ( zipValue == '' ){ inputZip.focus(); } else { inputQuery.focus(); } }); }); } // Submit-knappen submitBtn?.addEventListener('click', function(event) { event.preventDefault(); const isQueryValid = inputQuery.checkValidity(); const isZipValid = inputZip.checkValidity(); if (!isQueryValid) return inputQuery.reportValidity(); if (!isZipValid) return inputZip.reportValidity(); const query = inputQuery.value.trim(); const zipcode = inputZip.value.trim().replace(/\D/g, ''); if (zipcode !== '') { handleQuery(query, zipcode); } else { inputZip.focus(); } }); function fetchSuggestions(query) { query = query.trim(); if (query.length < 3 || !suggestionDropdown){ suggestionDropdown.style.display = "none"; } else { fetch("https://covestor.no/TreBeste.aspx?Fn=SearchCategory&Search=" + encodeURIComponent(query)) .then(response => response.json()) .then(data => { const suggestions = [...(data.result || []), ...(data.related || [])]; suggestionDropdown.innerHTML = ""; if (suggestions.length === 0) { suggestionDropdown.style.display = "none"; return; } suggestions.forEach(text => { const div = document.createElement("div"); div.className = "suggestion_item"; div.textContent = text; div.addEventListener("click", () => { inputQuery.value = text; suggestionDropdown.style.display = "none"; const zipValue = inputZip.value.trim(); if (zipValue !== '') { handleQuery(text, zipValue); } else { inputZip.focus(); } }); suggestionDropdown.appendChild(div); }); suggestionDropdown.style.display = "table"; }) .catch(err => { console.error("Feil ved henting av forslag:", err); suggestionDropdown.style.display = "none"; }); } } document.addEventListener("click", function (e) { if ( suggestionDropdown && !suggestionDropdown.contains(e.target) && e.target !== inputQuery) { suggestionDropdown.style.display = "none"; } }); document.addEventListener("keydown", function (e) { if ( suggestionDropdown && suggestionDropdown.style.display !== "none") { const items = suggestionDropdown.querySelectorAll(".suggestion_item"); if (e.key === "ArrowDown") { e.preventDefault(); activeIndex = (activeIndex + 1) % items.length; updateActive(items); } else if (e.key === "ArrowUp") { e.preventDefault(); activeIndex = (activeIndex - 1 + items.length) % items.length; updateActive(items); } else if (e.key === "Enter") { if (activeIndex >= 0 && activeIndex < items.length) { items[activeIndex].click(); } } } }); function updateActive(items) { items.forEach((item, index) => { if (index === activeIndex) { item.classList.add("active_suggestion"); item.scrollIntoView({ block: "nearest" }); } else { item.classList.remove("active_suggestion"); } }); } inputQuery?.addEventListener("input", function() { fetchSuggestions(this.value); }); // Expand kompakt form hvis nødvendig function expandFullFormIfCompact() { if (inputZip.style.display === 'none' || submitBtn.style.display === 'none') { const parent = inputQuery.parentElement; parent.style.display = ''; parent.style.alignItems = ''; inputQuery.style.flex = ''; inputQuery.style.minHeight = ''; inputQuery.style.height = ''; inputQuery.style.width = ''; inputZip.style.display = ''; inputZip.style.marginTop = '6px'; submitBtn.style.display = ''; submitBtn.style.marginTop = '8px'; document.getElementById("dynamic-search-icon")?.parentElement?.remove(); if (dynamicSuggestionBox) { dynamicSuggestionBox.style.display = 'none'; dynamicSuggestionBox.style.overflow = 'hidden'; } if (dynamicSuggestionIconBox) { dynamicSuggestionIconBox.style.display = ''; dynamicSuggestionIconBox.style.overflow = 'hidden'; } const instructions = document.getElementById("instructions"); if (instructions) { const p = instructions.querySelector("p"); if (p) p.style.display = ''; } inputQuery.focus(); } } inputQuery?.addEventListener("focus", expandFullFormIfCompact); inputQuery?.addEventListener("click", expandFullFormIfCompact); inputQuery?.addEventListener("keydown", expandFullFormIfCompact); // Tap for query const suggestionWrapper = document.getElementById('suggestion_wrapper'); if ( inputQuery ){ inputQuery.addEventListener('keydown', function (e) { if (e.key === 'Tab') { const currentValue = inputQuery.value.trim().toLowerCase(); if (!currentValue) return; const options = suggestionWrapper.querySelectorAll('.query_option'); // If exact match already exists, let Tab behave normally for (let option of options) { if (option.textContent.trim().toLowerCase() === currentValue) { return; // do not preventDefault } } // Otherwise, autocomplete to first startsWith match for (let option of options) { const text = option.textContent.trim(); if (text.toLowerCase().startsWith(currentValue)) { e.preventDefault(); inputQuery.value = text + ' '; return; } } } }); } // Delete all cookie const cookieDeleteBtn = document.getElementById("cookie_delete"); if ( cookieDeleteBtn ){ cookieDeleteBtn.addEventListener("click", function () { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookieName = cookies[i].split("=")[0].trim(); document.cookie = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; } alert("Alle cookies fra TreBeste.no er slettet."); }); } document.addEventListener('click', function (event) { const itemButton = event.target.closest('.top-3-list .company-item'); const contactusButton = event.target.closest('.contactus'); const loginButton = event.target.closest('.login'); if ( itemButton ){ createContactForm(); } if ( contactusButton ){ createContactUs(); } if ( loginButton ){ createLoginForm(); } }); });