
//- Sidecar background
function isUrlValid() {
const url = window.location.href; // Get the current URL
// Check for 4 or more forward slashes in the URL
const slashCount = (url.match(/\//g) || []).length;
if (slashCount < 4) return false;
// Check for specific URL formats (Issue+[no.] or Journal+[no.])
const magazineIssuePattern = /\/magazine\/category\/Issue\+\d+/;
const journalIssuePattern = /\/journal\/category\/Journal\+\d+/;
if (magazineIssuePattern.test(url) || journalIssuePattern.test(url)) return false;
// Check for excluded strings in the URL
const excludedStrings = ['www.kentarchaeology.org.uk/search', '/category/', '/tag/', '/shop/', '/models/', '/maps/', '/images/', '/videos/', '/audio/'];
for (const str of excludedStrings) {
if (url.includes(str)) return false;
}
// Check for URLs containing '/affiliates/', '/groups/', or '/grants/' unless they also contain '/category/'
const restrictedPaths = ['/affiliates/', '/groups/', '/grants/'];
for (const path of restrictedPaths) {
if (url.includes(path) && !url.includes('/category/')) return false;
}
return true;
}
// Function to insert the sidebar
function insertSidebar() {
const sidebar = document.createElement('div'); // Create a new div element
sidebar.className = 'iconsbackground'; // Assign the class 'iconsbackground' to the div
sidebar.style.width = '50px';
sidebar.style.height = '100vh'; // Full viewport height
sidebar.style.position = 'fixed';
sidebar.style.top = '0';
sidebar.style.right = '0'; // Align to the right side of the page
sidebar.style.backgroundColor = 'white';
sidebar.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.1)'; // Add shadow around the div
sidebar.style.zIndex = '100'; // Set a high z-index to ensure visibility
document.body.appendChild(sidebar); // Append the new div to the body
applyCustomStyles(); // Apply the additional CSS
}
// Function to apply custom CSS
function applyCustomStyles() {
const style = document.createElement('style');
style.textContent = `
/* Basic styling for body */
@media (min-width: 800px) {
content {
margin: 10px; /* Apply the margin to content element */
}
}
`;
document.head.appendChild(style); // Append the style to the document head
}
// Function to check and insert the sidebar if the screen is wider than 800px
function checkScreenWidth() {
if (window.innerWidth > 800 && !document.querySelector('.iconsbackground')) {
insertSidebar();
} else if (window.innerWidth <= 800) {
const sidebar = document.querySelector('.iconsbackground');
if (sidebar) {
sidebar.remove(); // Remove the sidebar if the screen width is 800px or less
}
}
}
// Initial check when the page loads
window.addEventListener('load', function() {
if (isUrlValid()) checkScreenWidth();
});
// Event listener for window resize to check if width changes
window.addEventListener('resize', function() {
if (isUrlValid()) checkScreenWidth();
});
//- Sidebar and icons on narrow screens
document.addEventListener('DOMContentLoaded', function () {
var allowedPaths = ['/news', '/books', '/papers', '/journal', '/events', '/services', '/reports', '/magazine', '/search', '/reports', '/members', '/audio', '/images', '/maps', '/documents', '/models', '/guidance', '/notes', '/records', '/join', '/contact', '/shop', '/support', '/stores', '/videos', '/about', '/collections', '/library', '/grants', '/affiliates', '/groups', '/members', '/people'];
var currentPath = window.location.pathname;
var isAllowedPath = allowedPaths.some(path => currentPath.includes(path));
var isScreenWidthValid = window.innerWidth > 800;
if (!isAllowedPath) return;
var isSidebarOpen = isScreenWidthValid;
var sidebar = document.querySelector('.sidebar');
var content = document.querySelector('.content');
var iframeContainer = document.querySelector('.iframe-container');
var iconWrapper;
function toggleIconsVisibility(isVisible) {
var icons = document.querySelectorAll('.map-icon, .topicons-background, .library-icon, .linked-data-icon, .tags-icon, .comment-icon-container, .data-icon, .custom-arrow-left, .lefticons-background, .search-icon, .link-icon, .timeline-icon, #restoreIcon, .citations-icon');
icons.forEach(icon => icon.style.visibility = isVisible ? 'visible' : 'hidden');
}
function updateIconPosition() {
if (iconWrapper) {
if (!isScreenWidthValid) {
iconWrapper.style.top = 'calc(var(--header-height, 0px) - 15px)';
iconWrapper.style.left = '-4px';
iconWrapper.style.transform = 'none';
} else {
iconWrapper.style.top = '15vh';
iconWrapper.style.left = '10px';
iconWrapper.style.transform = 'none';
}
}
}
function resizeIcon(isLarge) {
if (iconWrapper) {
iconWrapper.style.transform = isLarge ? 'scale(2)' : 'scale(1)';
}
}
function toggleSidebar() {
isSidebarOpen = !isSidebarOpen;
if (isScreenWidthValid) {
sidebar.style.left = isSidebarOpen ? '0' : '-35vw';
content.style.paddingLeft = isSidebarOpen ? '35vw' : '0';
} else {
sidebar.style.display = isSidebarOpen ? 'block' : 'none';
}
if (iframeContainer && window.innerWidth <= 750) {
iframeContainer.style.display = isSidebarOpen ? 'none' : '';
}
if (iconWrapper) {
iconWrapper.setAttribute('title', isSidebarOpen ? 'Hide navigation' : 'Show navigation');
const iconImg = iconWrapper.querySelector('img');
iconImg.src = isSidebarOpen ? '/s/icon-arrow-right.svg' : '/s/icon-navigation.svg'; // Toggle icon
}
toggleIconsVisibility(isSidebarOpen);
updateIconPosition();
}
function createIcon() {
iconWrapper = document.createElement('div');
iconWrapper.id = 'icon-wrapper';
iconWrapper.style.position = 'fixed';
iconWrapper.style.top = isScreenWidthValid ? '15vh' : 'calc(var(--header-height, 0px) + 25px)';
iconWrapper.style.marginTop = '0';
iconWrapper.style.left = isScreenWidthValid ? '10px' : '2.5vh';
iconWrapper.style.transform = isScreenWidthValid ? 'none' : 'scale(1.8)';
iconWrapper.style.width = '35px';
iconWrapper.style.cursor = 'pointer';
iconWrapper.style.zIndex = '9999';
iconWrapper.style.transition = 'transform 0.3s ease-out, top 0.3s ease-out, left 0.3s ease-out';
iconWrapper.setAttribute('title', isSidebarOpen ? 'Hide info' : 'Show info');
const iconImg = document.createElement('img');
iconImg.src = isSidebarOpen ? '/s/icon-arrow-right.svg' : '/s/icon-navigation.svg'; // Set initial icon correctly
iconImg.style.width = '100%';
iconImg.style.height = '100%';
iconImg.alt = 'Navigation Icon';
iconWrapper.appendChild(iconImg);
document.body.appendChild(iconWrapper);
iconWrapper.addEventListener('click', toggleSidebar);
if (!isScreenWidthValid) {
resizeIcon(true);
}
}
function handleScroll() {
if (!isScreenWidthValid) {
resizeIcon(false);
iconWrapper.style.left = '-4px';
iconWrapper.style.transform = 'scale(1)';
window.removeEventListener('scroll', handleScroll);
}
}
createIcon();
toggleIconsVisibility(isSidebarOpen);
if (!isScreenWidthValid) {
sidebar.style.display = 'none';
isSidebarOpen = false;
window.addEventListener('scroll', handleScroll);
}
window.addEventListener('resize', function () {
isScreenWidthValid = window.innerWidth > 800;
if (!isScreenWidthValid) {
isSidebarOpen = false;
sidebar.style.display = 'none';
toggleIconsVisibility(false);
} else {
isSidebarOpen = true;
sidebar.style.display = 'block';
toggleIconsVisibility(true);
}
updateIconPosition();
});
});
//- Redirect for Journal page
// JavaScript to handle redirect on link click
document.addEventListener("DOMContentLoaded", function() {
// Select all anchor tags within the div with id="index"
const indexDiv = document.querySelector("#index");
if (!indexDiv) return; // Exit if the div does not exist
const links = indexDiv.querySelectorAll("a[href^='/journal/']");
links.forEach(link => {
// Add a click event listener to each link
link.addEventListener("click", function(event) {
event.preventDefault(); // Prevent the default action
// Extract the journal number from the href attribute
const journalNumber = link.getAttribute("href").match(/\/journal\/(\d+)/)[1];
// Construct the new URL
const newUrl = `/journal/category/Volume+${journalNumber}`;
// Redirect to the new URL
window.location.href = newUrl;
});
});
});
// Sidebar resize
(function () {
let lastWidth = window.innerWidth;
function updateSidebarState() {
const sidebar = document.querySelector('.sidebar');
const contentElements = document.querySelectorAll('.content'); // Select all .content elements
if (!sidebar) return;
const isVisible = window.getComputedStyle(sidebar).display !== 'none';
if (lastWidth <= 800 && window.innerWidth > 800) {
// Transitioning from under 800px to over 800px
if (!isVisible) {
sidebar.style.display = 'block'; // Make sidebar visible
sidebar.style.left = '0px'; // Reset the left position
}
sidebar.style.width = '35vw'; // Reset sidebar width to 35vw
} else if (lastWidth > 800 && window.innerWidth <= 800) {
// Transitioning from over 800px to under 800px
if (isVisible) {
sidebar.style.display = 'none'; // Hide sidebar
sidebar.style.left = ''; // Clear any left position
}
contentElements.forEach(content => {
content.style.paddingLeft = '0'; // Reset padding-left of all .content elements
});
sidebar.style.width = '90vw'; // Reset sidebar width to 90vw
}
// Update the last known width
lastWidth = window.innerWidth;
}
// Add resize event listener
window.addEventListener('resize', updateSidebarState);
})();
//- Index for Journal pages
document.addEventListener('DOMContentLoaded', () => {
// Check if the current URL includes '/journal/'
if (window.location.href.includes('/journal/')) {
console.log('Script not executed because URL contains "/journal/".');
return; // Exit the script
}
// Get the elements
const indexDiv = document.getElementById('index');
const sidebarDiv = document.querySelector('.sidebar');
// Check if both elements exist
if (indexDiv && sidebarDiv) {
// Move the contents of #index to .sidebar
while (indexDiv.firstChild) {
sidebarDiv.appendChild(indexDiv.firstChild);
}
} else {
console.error('Either #index or .sidebar does not exist.');
}
});
//- Sidebar index
document.addEventListener("DOMContentLoaded", function () {
// ---------- Helper: Count slashes ----------
function countForwardSlashes(url) {
const urlWithoutProtocol = url.replace(/^https?:\/\//, '');
return (urlWithoutProtocol.match(/\//g) || []).length;
}
// ---------- Helper: Should index run on this page? ----------
const url = window.location.href;
const slashCount = countForwardSlashes(url);
const specialStrings = ['/journal', '/magazine', '/records', '/notes', '/affiliates', '/grants', '/groups'];
const containsSpecialString = specialStrings.some(str => url.includes(str));
const shouldIndexRun = (slashCount === 2) || (slashCount === 3 && containsSpecialString);
// ---------- Index Builder Function ----------
function buildSidebarIndex() {
const sidebar = document.querySelector('.sidebar');
if (!sidebar) return;
const container = document.querySelector('.blog-item-inner-wrapper');
if (!container) return;
const headers = Array.from(container.querySelectorAll('h1, h2, h3, h4'));
// Filter out first
let firstH1Skipped = false;
const filteredHeaders = headers.filter(header => {
if (header.tagName === 'H1' && !firstH1Skipped) {
firstH1Skipped = true;
return false;
}
return true;
});
if (filteredHeaders.length === 0) return;
// Clear previous index (avoid duplicates)
const existing = sidebar.querySelector('.dynamic-index');
if (existing) existing.remove();
const wrapperDiv = document.createElement('div');
wrapperDiv.className = 'dynamic-index';
const indexTitle = document.createElement('h2');
indexTitle.textContent = 'Index';
indexTitle.style.marginLeft = '10px';
wrapperDiv.appendChild(indexTitle);
const indexList = document.createElement('ul');
filteredHeaders.forEach((header, index) => {
if (!header.id) header.id = `header-${index}-${Date.now()}`;
const level = parseInt(header.tagName.replace('H', ''), 10);
const listItem = document.createElement('li');
listItem.style.marginLeft = `${(level - 1) * 20}px`;
const link = document.createElement('a');
link.textContent = header.textContent;
link.href = `#${header.id}`;
listItem.appendChild(link);
indexList.appendChild(listItem);
});
wrapperDiv.appendChild(indexList);
sidebar.appendChild(wrapperDiv);
}
// ---------- Trigger initial index ----------
if (shouldIndexRun) buildSidebarIndex();
// ---------- Dynamic Content Loader for /records/ ----------
if (url.includes("/records/")) {
const allParagraphs = document.querySelectorAll("p");
if (allParagraphs.length <= 250) return;
const wrapper = document.createElement("div");
wrapper.id = "read-more-wrapper";
wrapper.style.height = "1px";
wrapper.style.overflow = "hidden";
document.body.appendChild(wrapper);
let contentLoaded = false;
let loadMoreBtn = null;
async function loadContent() {
if (contentLoaded) return;
contentLoaded = true;
if (loadMoreBtn) loadMoreBtn.remove();
const htmlUrl = url.replace("/records/", "/html/records/");
try {
const response = await fetch(htmlUrl);
if (!response.ok) throw new Error("Page not found");
const htmlText = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, "text/html");
const htmlContent = doc.querySelector(".sqs-block-content .sqs-html-content");
if (!htmlContent) throw new Error("No .sqs-html-content found");
const cloned = htmlContent.cloneNode(true);
const firstH1 = cloned.querySelector("h1");
if (firstH1) firstH1.remove();
const targetContainer = document.querySelector(".sqs-block-content .sqs-html-content");
if (targetContainer) {
targetContainer.appendChild(cloned);
buildSidebarIndex(); // <-- Trigger index rebuild after content is added
}
} catch (err) {
console.error("Error loading content:", err);
const p250 = allParagraphs[249];
const redLine = document.createElement("hr");
redLine.style.border = "none";
redLine.style.borderTop = "3px solid red";
redLine.style.margin = "30px 0";
if (p250 && p250.parentNode) {
p250.parentNode.insertBefore(redLine, p250.nextSibling);
}
}
}
// Scroll Trigger
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
loadContent();
obs.unobserve(wrapper);
}
});
});
observer.observe(wrapper);
// Ctrl+F / Cmd+F
window.addEventListener("keydown", function (e) {
const isMac = navigator.platform.toUpperCase().includes("MAC");
if ((isMac && e.metaKey && e.key === "f") || (!isMac && e.ctrlKey && e.key === "f")) {
setTimeout(loadContent, 100);
}
});
// .search-icon trigger
const watchSearchIcon = () => {
const icon = document.querySelector(".search-icon");
if (icon) {
icon.addEventListener("click", loadContent);
icon.addEventListener("focus", loadContent);
} else {
setTimeout(watchSearchIcon, 500);
}
};
watchSearchIcon();
// Load More Button
const watchSidebar = () => {
const sidebar = document.querySelector(".sidebar");
if (!sidebar) {
setTimeout(watchSidebar, 500);
return;
}
const indexSection = sidebar.querySelector(".dynamic-index ul");
if (!indexSection) {
setTimeout(watchSidebar, 500);
return;
}
loadMoreBtn = document.createElement("button");
loadMoreBtn.textContent = "Load More";
loadMoreBtn.className = "load-more-archive-button";
loadMoreBtn.style.marginTop = "20px";
loadMoreBtn.style.padding = "8px 16px";
loadMoreBtn.style.cursor = "pointer";
loadMoreBtn.style.fontSize = "14px";
loadMoreBtn.addEventListener("click", loadContent);
indexSection.insertAdjacentElement("afterend", loadMoreBtn);
};
setTimeout(watchSidebar, 3000);
// Auto-load fallback after 5 seconds if not already triggered
setTimeout(() => {
if (!contentLoaded) {
console.log("Auto-loading extra content after 5s delay");
loadContent();
}
}, 5000);
}
});
//- Sidebar next and previous links
document.addEventListener('DOMContentLoaded', () => {
// Select the element with the specific class
const paginationElement = document.querySelector('.item-pagination.item-pagination--prev-next');
const sidebarDiv = document.querySelector('.sidebar');
// Check if both elements exist
if (paginationElement && sidebarDiv) {
// Append the entire element to the sidebar
sidebarDiv.appendChild(paginationElement);
} else {
console.error('Either .item-pagination.item-pagination--prev-next or .sidebar does not exist.');
}
});








