        function tmpl(template, replacements) {
            let result = template;
            for (const [key, value] of Object.entries(replacements)) {
                result = result.replace(new RegExp(`{${key}}`, 'g'), value);
            }
            return result;
        }

        function get_album_img(post_id, imgurl, cls){
            return tmpl(album_img_html, {
                'post_id': post_id,
                'imgurl': imgurl,
                'class': cls
            });
        }

        function square(x) {
            return x * x;
        }

        function get_album(divclass, create_id, name, val, ncount, datapid, slevel){
            create_id = parseInt(create_id);
            datapid = parseInt(datapid);

            return tmpl(album_html, {
                'ndivclass': divclass,
                'ncreate_id': create_id,
                'name': name,
                'val': val,
                'ncount': ncount,
                'ndatapid': datapid,
                'nslevel': slevel
            });
        }

        function get_add(){
            return add_html;
        }

        function get_select_item(liclass, sslevel, type_id, create_id, name, val){
            type_id = parseInt(type_id, 10);
            create_id = parseInt(create_id, 10);
            if (sslevel!=level) {return '';}
            return tmpl(select_item_html, {
                'liclass': liclass,
                'level': sslevel,
                'type_id': type_id,
                'create_id': create_id,
                'name': name,
                'val': val
            });
        }

        function get_edit_club(post_id, imgurl){
            return tmpl(edit_club_html, {
                'post_id': post_id,
                'imgurl': imgurl
            });
        }

        function get_delete_wnd(){
            html =  delete_wnd_hmtl;
            return html;
        }      

        function get_nav(){
            html =  get_nav_html;
            return html;
        }  



        function load_single_photo(img_id){
            html =  single_photo_html; 
           
            const photoIds = Object.keys(photo_arr);
           // const currentIndex = photoIds.indexOf(window.img_id);
            currentIndex  = window.img_id;
            img_ind_n = currentIndex + 1;
            img_ind_p = currentIndex ;
            
     
            if (window.img_ind_n>photoIds.length-1){
                img_ind_n = 0;
            }
            if (img_ind_p < 0){
                img_ind_p = photoIds.length-1;
            }
            //img_id_n = photoIds[img_ind_n];
            //img_id_p = photoIds[img_ind_p];

            img_id_n = $('.album_img').eq(img_ind+1).attr('id');
            img_id_n = img_id_n ?? $('.album_img').eq(0).attr('id');
            img_id_p = $('.album_img').eq(img_ind-1).attr('id');
            img_id_p = img_id_p??img_id_n;
            url  = photo_arr[window.img_id]['url'].replace('300', '1024');;
       
            desc = photo_arr[window.img_id]['desc'].replace('300', '1024');;
            if (desc!=''){
            help_text(desc,8000);
            }else{
                $('.help_icon,.help_text').hide();
            }
            url_n  = photo_arr[window.img_id_n]['url'].replace('300', '1024');;     
        
            url_p  = photo_arr[window.img_id_p]['url'].replace('300', '1024');
        
            get_single(url,desc,url_p,url_n);

          
         
        }  

        

        function get_single_photo(ind){
            html = single_photo_html;

            $(".lightbox__img_photo").addClass('lslide');

            $(".lightbox__img_photo img").eq(0).css('margin-bottom','-100%');
            //$(".lightbox__img_photo img").eq(0).css('position','absolute');
         

            phimg = light_phimg[ind]+'<buff>'+light_phimg[ind-1]+light_phimg[ind+1]+'</buff>'
            $(".lightbox__img_photo").html(phimg);

            img_id = light_phid[img_ind];
        
            $(".lightbox_comments").load('/wp-content/themes/album2/get_comments_lightbox.php',{id: img_id});


            $(".lightbox__author").load('/wp-content/themes/album2/get_user_avatar.php',{id: img_id});
            showlightbox(true);

            return html;
        }



function attach_to_dz(imageUrl) {
    $('.lightbox__create_name-input').val(title);
    $('#vkalbum_url').val(link);

    // Получение изображения и создание Blob
    fetch(imageUrl)
        .then(res => res.blob()) // Преобразование ответа в Blob
        .then(blob => {
            // Создание объекта FormData
            var formData = new FormData();
            formData.append('file', blob, imageUrl); // Добавление изображения как 'file'

            // Отправка FormData с изображением на сервер через AJAX
            $.ajax({
                url: '/wp-content/themes/album2/create_upload.php', // Путь к скрипту обработчику
                type: 'POST',
                data: formData,
                processData: false, // Отключение обработки данных jQuery
                contentType: false, // Отключение установки типа содержимого jQuery
                success: function (data) {
                    console.log('Upload successful!');
                    $('.lightbox__create-elem').click();
                    $('#parser').show();
                   

                },
                error: function (xhr, status, error) {
                    console.error('Upload failed:', error);
                }
            });
        });
}


        function goodsize(size,imageUrl300, imageUrl1024,nw1024){
           if ((size == 300)&&(nw1024<400)){
             return imageUrl1024
           }

           if ((size == 1024)&&(nw1024>400)){
             return imageUrl1024
           }

           if ((size == 300)&&(nw1024>400)){
             return imageUrl300
           }

           if ((size == 1024)&&(nw1024<400)){
             return imageUrl1024
           }
           
        }

function get_single(url, desc, url_p, url_n) {

const loadImage = (baseUrl, callback) => {
    // Попытка загрузить изображение с суффиксом
    const loadImageWithSuffix = (url) => {
        const image = new Image();
        image.onload = () => callback(image);
        image.onerror = () => {
            // Если изображение с суффиксом не загружается, пытаемся загрузить без суффикса
            const urlWithoutSuffix = url.replace(/-1024(?=\.jpg$)/, '');
            if (url !== urlWithoutSuffix) {
                loadImageWithoutSuffix(urlWithoutSuffix);
            } else {
                console.error('Не удалось загрузить изображение.');
            }
        };
        image.src = url;
        $('.mimg').eq(1).detach();
    };

    // Попытка загрузить изображение без суффикса
    const loadImageWithoutSuffix = (url) => {
        const image = new Image();
        image.onload = () => callback(image);
        image.onerror = () => {
            console.error('Не удалось загрузить изображение.');
        };
        image.src = url;
    };

    // Начать с URL с суффиксом
    loadImageWithSuffix(baseUrl);
};



    const processImage = ( url, className) => {
        const nw1024 = 1024
        // Check if the URL contains '-1024.jpg' and replace it with '-300.jpg' for the smaller image version
        const url300 = url.includes('-1024.jpg') ? goodsize(300, url.replace('-1024.jpg', '-300.jpg'), url, nw1024) : goodsize(300, url.replace('.jpg', '-300.jpg'), url, nw1024);
        // Use the original URL for the final URL if '-1024.jpg' is present, otherwise, append '-1024.jpg' to the URL
        const urlFinal = url.includes('-1024.jpg') ? goodsize(1024, url, url, nw1024) : goodsize(1024, url.replace('.jpg', '-1024.jpg'), url, nw1024);

        // Create the image element with the appropriate URLs and class
        const imgElement = `<img class="${className}" srcset="${url} 1024w, ${url300} 300w" src="${urlFinal}" style="background: url(${url300})">`;
        let buff = $(".lightbox__img_photo .buff").html(); // Ensure 'buff' is declared with 'let'

        // Detach the second element with the given class name from the DOM
        $(`.${className}`).eq(1).detach();
        let url2 = url.replace(/-1024(?=\.jpg$)/, '');        
        
        // Append the image element to the appropriate container based on the className
        if (className === 'img_p' || className === 'img_n') {

            $(".lightbox__img_photo .buff").append(imgElement);
        } else {
            $(".lightbox__img_photo").css(`background`,`url(${url2})`);
            $(".lightbox__img_photo").html(`${imgElement}<div class="buff">${buff}</div>`); // Use 'div' with class 'buff'
        }
    };

    const showLightbox = () => showlightbox(true);

    const updateLightboxContent = (desc) => {
        $('.lightbox__title-text').text(desc);
        $(".lightbox_comments").load('/wp-content/themes/album2/get_comments_lightbox.php', { id: img_id });
        $(".lightbox__author").load('/wp-content/themes/album2/get_user_avatar.php', { id: img_id });
    };

    const setupHTML = () => {
        const html = single_photo_html;
        $('.lightbox__content').html(html);
        $(".lightbox__img_photo").addClass('lslide');
        $(".lightbox__img_photo img").eq(0).css('margin-bottom', '-100%');
    };

    const loadImages = () => {
        loadImage(url, (image) => {
            processImage( url, 'mimg');
        });

        loadImage(url_p, (image) => {
            processImage( url_p, 'img_p');
        });

        loadImage(url_n, (image) => {
            processImage( url_n, 'img_n');
        });
     
    };

    setupHTML();
    loadImages();
    updateLightboxContent(desc);
    showLightbox();
}

function add1x1ImageToDropzone(dropzoneInstance) {
    // Создаем пустое полотно (canvas) размером 1x1 пиксель
    let canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;

    // Получаем контекст и заполняем его, например, черным цветом
    let ctx = canvas.getContext('2d');
    ctx.fillStyle = '#000000'; // черный цвет
    ctx.fillRect(0, 0, 1, 1); // заполняем весь 1x1 пиксель

    // Преобразуем содержимое canvas в Data URL
    let dataURL = canvas.toDataURL('image/png');

    // Преобразуем Data URL в Blob (файл)
    function dataURLtoBlob(dataURL) {
        let arr = dataURL.split(','), mime = arr[0].match(/:(.*?);/)[1];
        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }

    let blob = dataURLtoBlob(dataURL);
    blob.name = '1x1_image.png'; // Задаем имя файла

    // Добавляем Blob (файл) в Dropzone
    let mockFile = { name: blob.name, size: blob.size, upload: { progress: 0 } };

    // Используем Dropzone для добавления файла
    dropzoneInstance.emit("addedfile", mockFile);
    dropzoneInstance.emit("thumbnail", mockFile, dataURL);
    dropzoneInstance.emit("complete", mockFile);

    // Помещаем файл в очередь для загрузки и запускаем аплоуд
    dropzoneInstance.files.push(mockFile); // Добавляем файл в список файлов Dropzone
    dropzoneInstance.enqueueFile(mockFile); // Ставим файл в очередь на загрузку
}
function continueDropzoneUpload(dropzoneInstance) {
    // Проверяем, есть ли файлы в очереди на загрузку
    if (dropzoneInstance.getQueuedFiles().length > 0) {
        // Запускаем процесс загрузки всех файлов в очереди
        dropzoneInstance.processQueue();
    }
}


function showlightbox(photo) {
    const lheight = $(document).height();
    const lightbox = $('.lightbox');
    const lightboxContent = $('.lightbox__content');
    const lightboxComments = $(".lightbox_comments");
    const swipe = $('.swipe');

    lightbox.css('min-height', '150vh');

    lightbox.show();
    
    const lbwidth = lightboxContent[0].offsetWidth;
    const lbheight = lightboxContent[0].offsetHeight;
    const scrollTop = $(window).scrollTop() + 40;

    $(".lightbox_comments").html();

    if (!photo) {
        const wheight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
        let wtop = (wheight - lbheight) / 2;
        wtop = (wtop < 60) ? 60 : wtop;

        lightboxContent.css({
            'margin-left': -lbwidth / 2,
            'margin-top': -lbheight / 2,
            'left': '50%'
        });

        lightbox.css({
            'height': lbheight + wtop,
            'position': 'fixed'
        });

  
    } else {
        $('body').addClass('single');
        $('body').css('overflow-y', 'scroll');
        spn('.lightbox');
        $('.spinner').show();
        lightbox.css('position', 'absolute');
        lightboxContent.css({
            'position': 'relative',
            'margin': scrollTop + 'px auto',
            'left': 'auto'
        });

       
    
    }
}


function extractYearFromTitle(title) {
    // Предполагаем, что год - это четырехзначное число в title
    const match = title.match(/\b(19|20)\d{2}\b/);
    return match ? parseInt(match[0], 10) : null;
  }
  
  function getIntervalForYear(year, intervals) {
    // Находим подходящий интервал для года
    return intervals.find(interval => {
      const [start, end] = interval.split('-').map(Number);
      return year >= start && year <= (end || start);
    }) || 'Unknown'; // Если не найден подходящий интервал, возвращаем 'Unknown'
  }
  

  
  // Ваши интервалы и данные
   intervals = [
    "2024",
    "2023",
    "2022",
    "2021",
    "2020",
    "2019",
    "2018",
    "2017",
    "2016",
    "2014-2015",
    "2011-2013",
    "2001-2010",
    "1992-2000",
    "1981-1992",
    "1971-1980",
    "1961-1970",
    "1947-1960",
    "1910-1947",
    "Unknown"
  ];
  
