const form = document.getElementById('merge-form');
const calendars = document.getElementById('calendars');
const addCalendarButton = document.getElementById('add-calendar');
const result = document.getElementById('result');
const resultInfo = document.querySelector('.result-info');
// Search functionality elements
const searchBtn = document.getElementById('search-btn');
const calendarSearch = document.getElementById('calendar-search');
const searchResult = document.getElementById('search-result');
// Variable to track if we're editing an existing calendar
let isEditing = false;
let currentCalendarName = '';
// Variable to track the index of the calendar being added
let calendarIndex = 1;
let mergedUrl = '';
// Function to validate URL format
function isValidUrl(url) {
const urlPattern = /^(https?:\/\/[^\s$.?#].[^\s]*)$/; // Regex for URL validation
return urlPattern.test(url);
}
// Function to extract calendar name from URL or input
function extractCalendarName(input) {
// If it's a URL, extract the last part of the path
if (input.startsWith('http')) {
try {
// Remove trailing slash if present
if (input.endsWith('/')) {
input = input.slice(0, -1);
}
// Extract the last part of the path
const url = new URL(input);
const pathParts = url.pathname.split('/').filter(part => part.length > 0);
// If there's a path part, use the last one
if (pathParts.length > 0) {
let lastPart = pathParts[pathParts.length - 1];
// Remove .ics extension if present
if (lastPart.endsWith('.ics')) {
lastPart = lastPart.slice(0, -4);
}
return lastPart;
}
} catch (e) {
console.error('Error parsing URL:', e);
}
}
// If not a URL or URL parsing failed, just return the input as is
return input;
}
// Event listener for the search button
if (searchBtn) {
searchBtn.addEventListener('click', searchCalendar);
// Also search when pressing Enter in the search field
if (calendarSearch) {
calendarSearch.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
searchCalendar();
}
});
}
}
// Function to search for a calendar
function searchCalendar() {
let calendarName = calendarSearch.value.trim();
if (!calendarName) {
searchResult.innerHTML = '
Please enter a calendar name
';
return;
}
// Extract just the calendar name if a URL was entered
calendarName = extractCalendarName(calendarName);
searchResult.innerHTML = '
Loading...
';
// Check if calendar exists
fetch(`/calendar-config/${calendarName}`)
.then(response => response.json())
.then(data => {
if (data.exists) {
searchResult.innerHTML = `