// Main JavaScript functionality document.addEventListener('DOMContentLoaded', async () => { // Fetch courses from MongoDB API async function fetchCourses() { try { const response = await fetch('https://learn.mongodb.com/api/v1/instructor-led-training-schedule'); const data = await response.json(); return data.courses; } catch (error) { console.error('Error fetching courses:', error); return []; } } // Group courses by month function groupCoursesByMonth(courses) { const now = new Date(); const currentMonth = now.getMonth(); const currentYear = now.getFullYear(); const grouped = { current: [], next: [], following: [] }; courses.forEach(course => { const courseDate = new Date(course.startDate); const courseMonth = courseDate.getMonth(); const courseYear = courseDate.getFullYear(); if (courseYear === currentYear) { if (courseMonth === currentMonth) { grouped.current.push(course); } else if (courseMonth === currentMonth + 1) { grouped.next.push(course); } else if (courseMonth === currentMonth + 2) { grouped.following.push(course); } } }); return grouped; } // Render courses to the DOM function renderCourses(courses, containerId) { const container = document.getElementById(containerId); container.innerHTML = ''; if (courses.length === 0) { container.innerHTML = '

No courses scheduled for this period.

'; return; } courses.forEach(course => { const card = document.createElement('custom-course-card'); card.setAttribute('title', course.title); card.setAttribute('date', new Date(course.startDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })); card.setAttribute('time', course.time); card.setAttribute('location', course.location); card.setAttribute('link', course.link); container.appendChild(card); }); } // Initialize the page async function init() { const courses = await fetchCourses(); const groupedCourses = groupCoursesByMonth(courses); renderCourses(groupedCourses.current, 'current-month-courses'); renderCourses(groupedCourses.next, 'next-month-courses'); renderCourses(groupedCourses.following, 'following-month-courses'); // Update month selector labels with actual month names const now = new Date(); const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; const buttons = document.querySelectorAll('.month-btn'); buttons[0].textContent = monthNames[now.getMonth()]; buttons[1].textContent = monthNames[(now.getMonth() + 1) % 12]; buttons[2].textContent = monthNames[(now.getMonth() + 2) % 12]; } init(); });