ЗАРЕЖДАНЕ НА ДАТА...
ЗАРЕЖДАНЕ НА ВРЕМЕТО... 00:00:00
Банер Списанието
Всичко важно. На едно място.
🔍
Започнете да пишете, за да търсите в новините.
Зареждане на водещите новини...

Акценти

Зареждане на новини...

Мнения & Коментари

Зареждане...

Вдъхновение

Мода и тенденции

Зареждане...
Вдъхновение

Кулинарно изкуство

Зареждане...

АРТ

Зареждане...
/* ========================================= АКТИВНА РУБРИКА ========================================= */ const categoryParam = new URLSearchParams( window.location.search ).get('category'); const activeCategory = categoryParam ? categoryParam.trim() : ''; function applyCategoryFilter(query) { if (activeCategory) { return query.eq( 'category', activeCategory ); } return query; } function updateCategoryTitle() { const title = document.querySelector( '.section-title' ); if ( title && activeCategory ) { title.textContent = activeCategory; } document.title = activeCategory ? `${activeCategory} — СПИСАНИЕТО.` : 'СПИСАНИЕТО - Дигитално издание'; } /* ========================================= DATE / TIME ========================================= */ function updateDateTime() { const now = new Date(); const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; document.getElementById( 'current-date' ).textContent = now .toLocaleDateString( 'bg-BG', options ) .toUpperCase(); document.getElementById( 'current-time' ).textContent = now.toLocaleTimeString( 'bg-BG' ); document.getElementById( 'current-year' ).textContent = now.getFullYear(); } updateDateTime(); setInterval( updateDateTime, 1000 ); /* ========================================= ЦИТАТ НА ДЕНЯ ========================================= */ function loadDailyQuote() { const quotes = [ '„Важното не е само какво се случва, а защо се случва.“', '„Добрата журналистика започва с любопитство и завършва с проверен факт.“', '„Въпросите често са началото на най-важните отговори.“', '„Смисълът се открива, когато погледнем отвъд заглавието.“', '„Новините информират. Контекстът помага да разберем.“', '„Един добре проверен факт струва повече от десет предположения.“', '„Промяната започва с въпрос.“', '„Понякога най-важното е скрито между редовете.“', '„Добрият текст не просто казва. Той кара читателя да мисли.“', '„Любопитството е двигателят на всяко истинско знание.“', '„Фактите са основата, а контекстът е посоката.“', '„Всеки ден носи нова история. Важно е да я видим.“', '„Истинският разговор започва там, където свършват готовите отговори.“', '„Добрата история остава с нас дълго след последния ред.“', '„Светът е голям, но важните истории са близо до нас.“' ]; const now = new Date(); const dayNumber = Math.floor( Date.UTC( now.getFullYear(), now.getMonth(), now.getDate() ) / 86400000 ); const quoteIndex = Math.abs(dayNumber) % quotes.length; const quoteElement = document.getElementById( 'daily-quote' ); if (quoteElement) { quoteElement.textContent = quotes[quoteIndex]; } } loadDailyQuote(); /* ========================================= ESCAPE HTML ========================================= */ function escapeHtml(value) { if ( value === null || value === undefined ) { return ''; } return String(value) .replace( /&/g, '&' ) .replace( //g, '>' ) .replace( /"/g, '"' ) .replace( /'/g, ''' ); } /* ========================================= ФОРМАТИРАНЕ НА ДАТА ========================================= */ function formatSearchDate( dateValue ) { if (!dateValue) { return ''; } const date = new Date(dateValue); if ( Number.isNaN( date.getTime() ) ) { return ''; } return date.toLocaleDateString( 'bg-BG' ); } /* ========================================= ТЪРСЕНЕ ========================================= */ let searchTimeout = null; function openSearchModal() { const modal = document.getElementById( 'searchModal' ); const input = document.getElementById( 'searchInput' ); const results = document.getElementById( 'searchResults' ); modal.classList.add( 'active' ); document.body.style.overflow = 'hidden'; results.innerHTML = `
Започнете да пишете, за да търсите в новините.
`; setTimeout( () => { input.focus(); }, 100 ); } function closeSearchModal() { const modal = document.getElementById( 'searchModal' ); modal.classList.remove( 'active' ); document.body.style.overflow = ''; } window.openSearchModal = openSearchModal; window.closeSearchModal = closeSearchModal; async function performSearch() { const input = document.getElementById( 'searchInput' ); const results = document.getElementById( 'searchResults' ); const searchTerm = input.value.trim(); if ( searchTerm.length < 2 ) { results.innerHTML = `
Въведете поне 2 символа за търсене.
`; return; } results.innerHTML = `
Търсене за „${escapeHtml(searchTerm)}“...
`; const words = searchTerm .toLowerCase() .split(/\s+/) .filter(Boolean); let data = []; try { const response = await fetch( 'https://spisanieto-api.spisanieto-news.workers.dev/api/news' ); if (!response.ok) { throw new Error('Cloudflare API error'); } const result = await response.json(); data = result.news || []; } catch (error) { console.error('Search Cloudflare error:', error); results.innerHTML = `
Възникна проблем при търсенето. Моля, опитайте отново.
`; return; } if ( !data || data.length === 0 ) { results.innerHTML = `
Все още няма публикувани новини за търсене.
`; return; } const matchedNews = data.filter( news => { const searchableText = [ news.title, news.subtitle, news.content, news.category, news.author ] .filter(Boolean) .join(' ') .toLowerCase(); return words.every( word => searchableText.includes( word ) ); } ); if ( matchedNews.length === 0 ) { results.innerHTML = `
Няма намерени новини за „${escapeHtml(searchTerm)}“.
`; return; } results.innerHTML = `
Намерени ${matchedNews.length} ${matchedNews.length === 1 ? 'резултат' : 'резултата'} за „${escapeHtml(searchTerm)}“
${matchedNews .map( news => { const image = news.image_url || 'https://images.unsplash.com/photo-1504711434969-e33886168f5c?auto=format&fit=crop&w=600&q=80'; const articleUrl = `article.html?id=${encodeURIComponent(news.id)}`; return ` ${escapeHtml(news.title)}
${escapeHtml( news.category || 'Новини' )}
${escapeHtml(news.title)}
${formatSearchDate( news.created_at )} ${ news.author ? ` · ${escapeHtml(news.author)}` : '' }
`; } ) .join('')} `; } document .getElementById( 'searchInput' ) .addEventListener( 'input', () => { clearTimeout( searchTimeout ); searchTimeout = setTimeout( performSearch, 350 ); } ); document .getElementById( 'searchInput' ) .addEventListener( 'keydown', event => { if ( event.key === 'Escape' ) { closeSearchModal(); } if ( event.key === 'Enter' ) { clearTimeout( searchTimeout ); performSearch(); } } ); document .getElementById( 'searchModal' ) .addEventListener( 'click', event => { if ( event.target.id === 'searchModal' ) { closeSearchModal(); } } ); /* ========================================= АКЦЕНТИ ========================================= */ async function loadHighlights() { const container = document.getElementById('highlights'); try { const response = await fetch( 'https://spisanieto-api.spisanieto-news.workers.dev/api/news' ); if (!response.ok) { throw new Error('Грешка при връзката с Cloudflare'); } const result = await response.json(); let data = result.news || []; if (activeCategory) { data = data.filter(news => news.category === activeCategory ); } data = data .sort((a, b) => new Date(b.created_at) - new Date(a.created_at) ) .slice(0, 8); if (!data.length) { container.innerHTML = `

В тази рубрика все още няма публикувани новини.

`; return; } container.innerHTML = data.map(news => { const image = news.image_url || 'https://images.unsplash.com/photo-1504711434969-e33886168f5c?auto=format&fit=crop&w=600&q=80'; const category = news.category || 'Новини'; const articleUrl = `article.html?id=${encodeURIComponent(news.id)}`; return `
${escapeHtml(news.title)} ${escapeHtml(category)} ${escapeHtml(news.title)}
`; }).join(''); } catch (error) { console.error('Cloudflare news error:', error); container.innerHTML = `

Възникна проблем при зареждането на новините.

`; } } /* ========================================= НАЙ-ЧЕТЕНИ ========================================= */ async function loadPopularNews() { const container = document.getElementById('popular-news'); try { const response = await fetch( 'https://spisanieto-api.spisanieto-news.workers.dev/api/news' ); if (!response.ok) { throw new Error('Cloudflare API error'); } const result = await response.json(); const data = (result.news || []) .sort((a, b) => { const viewsDifference = (b.views || 0) - (a.views || 0); if (viewsDifference !== 0) { return viewsDifference; } return new Date(b.created_at) - new Date(a.created_at); }) .slice(0, 5); if (!data.length) { container.innerHTML = ` `; return; } container.innerHTML = data.map((news, index) => { const articleUrl = `article.html?id=${encodeURIComponent(news.id)}`; return ` `; }).join(''); } catch (error) { console.error('Cloudflare popular news error:', error); container.innerHTML = ` `; } } /* ========================================= ПОСЛЕДНИ НОВИНИ ========================================= */ async function loadLatestNews() { const container = document.getElementById('latest-news'); if (!container) { console.warn('Latest news container not found.'); return; } try { const response = await fetch( 'https://spisanieto-api.spisanieto-news.workers.dev/api/news' ); if (!response.ok) { throw new Error('Cloudflare API error'); } const result = await response.json(); const data = (result.news || []) .filter(news => news.status === 'published' || news.status == null ) .sort((a, b) => new Date(b.created_at) - new Date(a.created_at) ) .slice(0, 5); if (!data.length) { container.innerHTML = `
  • Все още няма публикувани новини.
  • `; return; } container.innerHTML = data.map(news => { const articleUrl = `article.html?id=${encodeURIComponent(news.id)}`; const date = news.created_at ? new Date(news.created_at).toLocaleDateString('bg-BG') : ''; return `
  • ${escapeHtml(news.category || 'Новини')} ${escapeHtml(news.title)} ${date}
  • `; }).join(''); } catch (error) { console.error('Cloudflare Latest news error:', error); container.innerHTML = `
  • Не успяхме да заредим последните новини.
  • `; } } /* ========================================= ТЕМИ НА ФОКУС ========================================= */ async function loadFocusTopics() { const box = document.getElementById('focus-topics-box'); const container = document.getElementById('focus-topics'); try { const response = await fetch( 'https://spisanieto-api.spisanieto-news.workers.dev/api/news' ); if (!response.ok) { throw new Error('Cloudflare API error'); } const result = await response.json(); const data = (result.news || []) .filter(news => news.is_focus === 1 && (news.status === 'published' || news.status == null) ) .sort((a, b) => new Date(b.created_at) - new Date(a.created_at) ); if (!data.length) { if (box) box.style.display = 'none'; return; } if (box) box.style.display = ''; container.innerHTML = data.map(news => { const articleUrl = `article.html?id=${encodeURIComponent(news.id)}`; const date = news.created_at ? new Date(news.created_at).toLocaleDateString('bg-BG') : ''; const imageUrl = news.image_url ? String(news.image_url).trim() : ''; const image = imageUrl || 'https://images.unsplash.com/photo-1504711434969-e33886168f5c?auto=format&fit=crop&w=800&q=80'; return ` ${escapeHtml(news.title)} ${escapeHtml(news.category || 'Новини')} ${escapeHtml(news.title)} `; }).join(''); } catch (error) { console.error('Cloudflare focus topics error:', error); if (box) box.style.display = 'none'; } } /* ========================================= HERO ========================================= */ let slideIndex = 0; let heroSlides = []; let heroTimer = null; async function loadHero() { const container = document.getElementById('hero-slides'); try { const response = await fetch( 'https://spisanieto-api.spisanieto-news.workers.dev/api/news' ); if (!response.ok) { throw new Error('Cloudflare API error'); } const result = await response.json(); let data = (result.news || []) .filter(news => news.is_featured === 1 && (news.status === 'published' || news.status == null) ); if (activeCategory) { data = data.filter(news => news.category === activeCategory ); } data.sort((a, b) => new Date(b.created_at) - new Date(a.created_at) ); if (!data.length) { data = (result.news || []) .filter(news => news.status === 'published' || news.status == null ); if (activeCategory) { data = data.filter(news => news.category === activeCategory ); } data.sort((a, b) => new Date(b.created_at) - new Date(a.created_at) ); } data = data.slice(0, 4); if (!data.length) { container.innerHTML = `
    В тази рубрика все още няма публикувани новини.
    `; document.getElementById('hero-prev').style.display = 'none'; document.getElementById('hero-next').style.display = 'none'; return; } heroSlides = data; slideIndex = 0; container.innerHTML = data.map((news, index) => { const image = news.image_url || 'https://images.unsplash.com/photo-1504711434969-e33886168f5c?auto=format&fit=crop&w=1600&q=80'; const category = news.category || 'Новини'; const articleUrl = `article.html?id=${encodeURIComponent(news.id)}`; return ` `; }).join(''); document.getElementById('hero-prev').style.display = heroSlides.length > 1 ? 'block' : 'none'; document.getElementById('hero-next').style.display = heroSlides.length > 1 ? 'block' : 'none'; if (heroTimer) { clearInterval(heroTimer); } if (heroSlides.length > 1) { heroTimer = setInterval(() => { moveHeroSlide(1); }, 5000); } } catch (error) { console.error('Cloudflare Hero error:', error); container.innerHTML = `
    Възникна проблем при зареждането на водещите новини.
    `; document.getElementById('hero-prev').style.display = 'none'; document.getElementById('hero-next').style.display = 'none'; } } /* ========================================= SHOW HERO SLIDE ========================================= */ function showHeroSlide(index) { const slides = document.querySelectorAll( '.carousel-slide' ); if ( !slides.length ) { return; } slides.forEach( (slide, i) => { slide.classList.remove( 'active' ); if ( i === index ) { slide.classList.add( 'active' ); } } ); } /* ========================================= HERO NEXT / PREVIOUS ========================================= */ function moveHeroSlide(direction) { if ( heroSlides.length <= 1 ) { return; } slideIndex = ( slideIndex + direction + heroSlides.length ) % heroSlides.length; showHeroSlide( slideIndex ); } /* ========================================= HERO BUTTONS ========================================= */ document .getElementById( 'hero-prev' ) .addEventListener( 'click', () => { moveHeroSlide(-1); } ); document .getElementById( 'hero-next' ) .addEventListener( 'click', () => { moveHeroSlide(1); } ); /* ========================================= START ========================================= */ updateCategoryTitle(); loadHighlights(); loadPopularNews(); loadLatestNews(); loadFocusTopics(); loadHero(); /* ========================================= ABOUT MODAL ========================================= */ function openAboutModal() { document.getElementById( 'aboutModal' ).style.display = 'flex'; } function closeAboutModal() { document.getElementById( 'aboutModal' ).style.display = 'none'; } window.openAboutModal = openAboutModal; window.closeAboutModal = closeAboutModal; window.addEventListener( 'click', function(event) { const modal = document.getElementById( 'aboutModal' ); if ( event.target === modal ) { modal.style.display = 'none'; } } );