MediaWiki:Common.js: различия между версиями

Страница интерфейса MediaWiki
Нет описания правки
Нет описания правки
Строка 73: Строка 73:
     }
     }


     // Данные о законах SS14
     // Универсальная система подсказок для таблиц законов
    window.ss14Laws = {
(function() {
        '100': { name: 'Оскорбительное поведение', category: 1, minTime: 5, maxTime: 10 },
    'use strict';
        '101': { name: 'Лёгкий ущерб здоровью', category: 1, minTime: 5, maxTime: 10 },
   
        '102': { name: 'Порча имущества', category: 1, minTime: 5, maxTime: 10 },
    if (window.lawTooltipsLoaded) return;
        '103': { name: 'Мелкая кража', category: 1, minTime: 5, maxTime: 10 },
    window.lawTooltipsLoaded = true;
        '104': { name: 'Владение регулируемыми веществами', category: 1, minTime: 5, maxTime: 10 },
   
        '105': { name: 'Злоупотребление экипировкой', category: 1, minTime: 5, maxTime: 10 },
    // Функция загрузки Tippy.js
         '106': { name: 'Помеха работе сотрудников', category: 1, minTime: 5, maxTime: 10 },
    function loadTippy(callback) {
        '107': { name: 'Проникновение', category: 1, minTime: 5, maxTime: 10 },
         if (window.tippy) {
        '108': { name: 'Жестокое обращение с животными', category: 1, minTime: 5, maxTime: 10 },
            callback();
         '109': { name: 'Клевета', category: 1, minTime: 5, maxTime: 10 },
            return;
         }
          
          
         '200': { name: 'Оскорбление власти', category: 2, minTime: 10, maxTime: 15 },
         var popperScript = document.createElement('script');
         '201': { name: 'Средний ущерб здоровью', category: 2, minTime: 10, maxTime: 15 },
         popperScript.src = 'https://unpkg.com/@popperjs/core@2/dist/umd/popper.min.js';
        '202': { name: 'Вандализм', category: 2, minTime: 10, maxTime: 15 },
         popperScript.onload = function() {
         '204': { name: 'Распространение регулируемых веществ', category: 2, minTime: 10, maxTime: 15 },
            var tippyScript = document.createElement('script');
        '205': { name: 'Владение боевым приспособлением', category: 2, minTime: 10, maxTime: 15 },
            tippyScript.src = 'https://unpkg.com/tippy.js@6/dist/tippy-bundle.umd.min.js';
        '206': { name: 'Помеха правосудию', category: 2, minTime: 10, maxTime: 15 },
            tippyScript.onload = callback;
        '207': { name: 'Проникновение со взломом', category: 2, minTime: 10, maxTime: 15 },
            document.head.appendChild(tippyScript);
        '208': { name: 'Убийство животного', category: 2, minTime: 10, maxTime: 15 },
         };
         '209': { name: 'Халатность', category: 2, minTime: 10, maxTime: 15 },
         document.head.appendChild(popperScript);
         '210': { name: 'Ограничение свободы', category: 2, minTime: 10, maxTime: 15 },
        '211': { name: 'Шпионаж', category: 2, minTime: 10, maxTime: 15 },
          
          
         '300': { name: 'Забастовка', category: 3, minTime: 15, maxTime: 20, dismissal: true },
         var tippyCSS = document.createElement('link');
         '301': { name: 'Тяжкий ущерб здоровью', category: 3, minTime: 15, maxTime: 20, dismissal: true },
         tippyCSS.rel = 'stylesheet';
         '302': { name: 'Саботаж', category: 3, minTime: 15, maxTime: 20, dismissal: true },
         tippyCSS.href = 'https://unpkg.com/tippy.js@6/dist/tippy.css';
         '303': { name: 'Кража', category: 3, minTime: 15, maxTime: 20, dismissal: true },
         document.head.appendChild(tippyCSS);
        '304': { name: 'Оборот контрабанды', category: 3, minTime: 15, maxTime: 20, dismissal: true },
    }
        '305': { name: 'Владение нелетальным оружием', category: 3, minTime: 15, maxTime: 20, dismissal: true },
      
        '306': { name: 'Мошенничество', category: 3, minTime: 15, maxTime: 20, dismissal: true },
     // Функция извлечения информации из детальных таблиц
        '307': { name: 'Проникновение в стратегическую точку', category: 3, minTime: 15, maxTime: 20, dismissal: true },
     function extractLawDataFromPage() {
        '308': { name: 'Распространение опасной флоры и фауны', category: 3, minTime: 15, maxTime: 20, dismissal: true },
         var lawData = {};
        '309': { name: 'Серьёзная халатность', category: 3, minTime: 15, maxTime: 20, dismissal: true },
        '310': { name: 'Похищение', category: 3, minTime: 15, maxTime: 20, dismissal: true },
        '311': { name: 'Проникновение в защищённый канал', category: 3, minTime: 15, maxTime: 20, dismissal: true },
       
        '400': { name: 'Бунт', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '401': { name: 'Убийство', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '403': { name: 'Крупная кража', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '404': { name: 'Производство регулируемых веществ', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '405': { name: 'Владение летальным оружием', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '406': { name: 'Растрата активов корпорации', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '408': { name: 'Убийство особого животного', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '409': { name: 'Грубая халатность', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '410': { name: 'Похищение должностного лица', category: 4, minTime: 20, maxTime: 25, dismissal: true },
        '411': { name: 'Антикорпоративный шпионаж', category: 4, minTime: 20, maxTime: 25, dismissal: true },
       
        '500': { name: 'Мятеж', category: 5, dClass: true, dismissal: true },
        '501': { name: 'Уничтожение тела', category: 5, dClass: true, dismissal: true },
        '502': { name: 'Крупный саботаж', category: 5, dClass: true, dismissal: true },
        '503': { name: 'Особая кража', category: 5, dClass: true, dismissal: true },
        '504': { name: 'Владение вражеским снаряжением', category: 5, dClass: true, dismissal: true },
        '505': { name: 'Распространение оружия', category: 5, dClass: true, dismissal: true },
        '507': { name: 'Проникновение в защищённую стратегическую точку', category: 5, dClass: true, dismissal: true },
        '510': { name: 'Похищение высокопоставленных лиц', category: 5, dClass: true, dismissal: true },
        '511': { name: 'Разглашение секретной информации', category: 5, dClass: true, dismissal: true }
     };
 
     // Глобальные функции для SS14 калькулятора
     window.ss14CurrentLawCode = null;
 
    window.toggleCalculator = function(lawCode) {
         var calculator = document.getElementById('ss14-calculator');
        window.ss14CurrentLawCode = lawCode;
          
          
         if (!calculator) return;
         // Ищем все таблицы с детальными описаниями
        var detailTables = document.querySelectorAll('.mw-collapsible-content table');
          
          
         if (calculator.style.display === 'none' || !calculator.classList.contains('active')) {
         detailTables.forEach(function(table) {
             calculator.classList.add('active');
             var rows = table.querySelectorAll('tr');
            generateLawCheckboxes();
              
              
             // Автоматически выбираем нажатый закон
             rows.forEach(function(row) {
            var checkbox = document.getElementById('law-' + lawCode);
                var cells = row.querySelectorAll('td');
            if (checkbox) {
                if (cells.length >= 3) {
                checkbox.checked = true;
                    var crimeCell = cells[0];
            }
                    var descriptionCell = cells[1];
           
                    var exampleCell = cells[2];
            calculateSentence();
                   
        } else {
                    // Ищем якорь с номером статьи
            calculator.classList.remove('active');
                    var anchor = crimeCell.querySelector('[id]');
        }
                    if (anchor) {
    };
                        var lawCode = anchor.id;
 
                        var titleElement = crimeCell.querySelector('b');
    window.generateLawCheckboxes = function() {
                       
        var container = document.getElementById('law-checkboxes');
                        if (titleElement && lawCode.match(/^\d{3}$/)) {
        if (!container) return;
                            var titleText = titleElement.textContent.trim();
                            var titleParts = titleText.split('\n\n');
                            var lawTitle = titleParts.length > 1 ? titleParts[1] : titleText;
                           
                            var description = descriptionCell.textContent.trim();
                           
                            // Извлекаем примеры из списка
                            var examples = [];
                            var exampleItems = exampleCell.querySelectorAll('li');
                            exampleItems.forEach(function(item) {
                                var text = item.textContent.trim();
                                if (text) {
                                    examples.push(text);
                                }
                            });
                           
                            lawData[lawCode] = {
                                title: lawTitle,
                                description: description,
                                examples: examples
                            };
                        }
                    }
                }
            });
        });
          
          
         container.innerHTML = '';
         return lawData;
    }
   
    // Функция создания HTML для подсказки
    function createTooltipContent(lawCode, lawData) {
        var data = lawData[lawCode];
        if (!data) return null;
          
          
        // Группируем законы по категориям
         var html = '<div class="law-tooltip">';
         var categories = {
        html += '<h4 class="law-tooltip-title">' + lawCode + ' - ' + data.title + '</h4>';
            1: { name: 'Лёгкие нарушения (1XX)', color: '#0F4F27' },
        html += '<p class="law-tooltip-description">' + data.description + '</p>';
            2: { name: 'Средние нарушения (2XX)', color: '#414700' },
            3: { name: 'Тяжкие нарушения (3XX)', color: '#611300' },
            4: { name: 'Особо тяжкие нарушения (4XX)', color: '#57000C' },
            5: { name: 'Критические нарушения (5XX)', color: '#121212' }
        };
          
          
         for (var cat = 1; cat <= 5; cat++) {
         if (data.examples && data.examples.length > 0) {
             var categoryDiv = document.createElement('div');
             html += '<div class="law-tooltip-examples">';
            categoryDiv.style.marginBottom = '15px';
             html += '<strong>Примеры:</strong>';
             categoryDiv.innerHTML = '<h5 style="color: ' + categories[cat].color + '; margin-bottom: 8px;">' + categories[cat].name + '</h5>';
            html += '<ul>';
              
             data.examples.slice(0, 5).forEach(function(example) { // Ограничиваем до 5 примеров
            var lawsInCategory = Object.keys(window.ss14Laws).filter(function(code) {
                 html += '<li>' + example + '</li>';
                return window.ss14Laws[code].category === cat;
            });
           
            lawsInCategory.forEach(function(code) {
                 var law = window.ss14Laws[code];
                var label = document.createElement('label');
                label.className = 'law-checkbox';
                label.innerHTML = '<input type="checkbox" id="law-' + code + '" onchange="calculateSentence()"> ' + code + ' - ' + law.name;
                categoryDiv.appendChild(label);
             });
             });
              
             html += '</ul>';
             container.appendChild(categoryDiv);
             html += '</div>';
         }
         }
    };
         html += '</div>';
 
    window.calculateSentence = function() {
        var selectedLaws = [];
         var checkboxes = document.querySelectorAll('[id^="law-"]:checked');
          
          
         checkboxes.forEach(function(checkbox) {
         return html;
            var lawCode = checkbox.id.replace('law-', '');
    }
            selectedLaws.push(lawCode);
   
        });
    // Инициализация подсказок
    function initTooltips() {
        var lawData = extractLawDataFromPage();
          
          
         if (selectedLaws.length === 0) {
         // Ищем все ссылки на статьи (и в основной таблице, и в детальных)
            var resultDiv = document.getElementById('calculation-result');
         var lawLinks = document.querySelectorAll('a[href*="#"]');
            if (resultDiv) {
                resultDiv.style.display = 'none';
            }
            return;
        }
       
         var modifierSelect = document.getElementById('modifier-select');
        var repeatOffense = document.getElementById('repeat-offense');
        var cooperation = document.getElementById('cooperation');
        var dClass = document.getElementById('d-class');
       
        var modifier = modifierSelect ? modifierSelect.value : 'none';
        var isRepeat = repeatOffense ? repeatOffense.checked : false;
        var hasCooperation = cooperation ? cooperation.checked : false;
        var isDClass = dClass ? dClass.checked : false;
          
          
         var result = calculatePunishment(selectedLaws, modifier, isRepeat, hasCooperation, isDClass);
         lawLinks.forEach(function(link) {
        displayResult(result, selectedLaws);
             var href = link.getAttribute('href');
    };
             var match = href.match(/#(\d{3})/);
 
    function calculatePunishment(selectedLaws, modifier, isRepeat, hasCooperation, isDClass) {
        var totalTime = 0;
        var punishmentType = 'Заключение под стражу';
        var hasDismissal = false;
        var hasDClass = false;
        var categoryGroups = {};
       
        // Группируем по категориям (одинаковые категории не складываются)
        selectedLaws.forEach(function(lawCode) {
             var law = window.ss14Laws[lawCode];
             var categoryCode = lawCode.substring(1); // получаем последние 2 цифры (тип нарушения)
              
              
             if (!categoryGroups[categoryCode] || law.category > window.ss14Laws[categoryGroups[categoryCode]].category) {
             if (match) {
                categoryGroups[categoryCode] = lawCode;
                var lawCode = match[1];
                var tooltipContent = createTooltipContent(lawCode, lawData);
               
                if (tooltipContent) {
                    tippy(link, {
                        content: tooltipContent,
                        allowHTML: true,
                        interactive: true,
                        placement: 'auto',
                        maxWidth: 450,
                        theme: 'law-theme',
                        arrow: true,
                        duration: [300, 200],
                        delay: [400, 100],
                        popperOptions: {
                            modifiers: [
                                {
                                    name: 'preventOverflow',
                                    options: {
                                        padding: 10
                                    }
                                },
                                {
                                    name: 'flip',
                                    options: {
                                        fallbackPlacements: ['top', 'bottom', 'right', 'left']
                                    }
                                }
                            ]
                        },
                        onShow: function(instance) {
                            // Скрываем другие открытые подсказки
                            document.querySelectorAll('[data-tippy-root]').forEach(function(tooltip) {
                                if (tooltip._tippy && tooltip._tippy !== instance) {
                                    tooltip._tippy.hide();
                                }
                            });
                        }
                    });
                }
             }
             }
         });
         });
          
          
         // Рассчитываем время для каждой группы
         console.log('Загружено подсказок для статей:', Object.keys(lawData).length);
        Object.keys(categoryGroups).forEach(function(categoryCode) {
            var lawCode = categoryGroups[categoryCode];
            var law = window.ss14Laws[lawCode];
           
            if (law.dClass) {
                hasDClass = true;
                totalTime += 70; // для расчёта модификаторов
            } else {
                totalTime += law.maxTime; // берём максимальное время
            }
           
            if (law.dismissal) {
                hasDismissal = true;
            }
        });
       
        // Применяем модификаторы
        switch (modifier) {
            case 'M-CLEM':
                // Помилование - только для категорий 3 и 4
                var hasEligibleLaws = Object.keys(categoryGroups).some(function(categoryCode) {
                    var lawCode = categoryGroups[categoryCode];
                    var law = window.ss14Laws[lawCode];
                    return law.category === 3 || law.category === 4;
                });
                if (hasEligibleLaws) {
                    totalTime = Math.max(0, totalTime - 10);
                }
                break;
               
            case 'M-SURR':
                // Немедленная капитуляция
                totalTime = Math.max(0, totalTime - 5);
                break;
               
            case 'M-DEFENSE':
            case 'M-HELP':
                // Самооборона или спасение - снимает все обвинения
                totalTime = 0;
                hasDClass = false;
                punishmentType = 'Обвинения сняты (требуется обыск)';
                break;
        }
       
        // Повторное нарушение
        if (isRepeat && totalTime > 0) {
            totalTime = Math.min(totalTime + 10, 50);
        }
       
        // Сотрудничество со следствием
        if (hasCooperation && totalTime > 0) {
            totalTime = Math.max(0, totalTime - 3);
        }
       
        // Определяем тип наказания
        if (hasDClass) {
            punishmentType = 'Перевод в Д-класс';
            if (modifier === 'M-LOW' && isDClass) {
                punishmentType = 'Условная ликвидация (M-LOW)';
            } else if (modifier === 'M-VITAL' && isDClass) {
                punishmentType = 'Взаимодействие с SCP (M-VITAL)';
            }
        } else if (totalTime >= 50) {
            punishmentType = 'Перевод в Д-класс (срок ≥50 мин)';
            if (totalTime >= 35 && isDClass) {
                punishmentType += ' или добровольный перевод';
            }
        } else if (totalTime >= 35 && isDClass) {
            punishmentType = 'Возможен добровольный перевод в Д-класс';
        }
       
        return {
            totalTime: totalTime,
            punishmentType: punishmentType,
            hasDismissal: hasDismissal,
            hasDClass: hasDClass,
            categoryGroups: categoryGroups
        };
     }
     }
 
   
     function displayResult(result, selectedLaws) {
    // Запуск после загрузки страницы
         var resultDiv = document.getElementById('calculation-result');
     function init() {
        if (!resultDiv) return;
         loadTippy(function() {
       
            // Ждем немного, чтобы все элементы MediaWiki загрузились
        var html = '<h4>📋 Результат расчёта:</h4>';
            setTimeout(initTooltips, 500);
       
        html += '<div><strong>Выбранные статьи:</strong><br>';
        selectedLaws.forEach(function(lawCode) {
            var law = window.ss14Laws[lawCode];
            html += '• ' + lawCode + ' - ' + law.name + '<br>';
         });
         });
        html += '</div><br>';
       
        html += '<div class="punishment-type">Тип наказания: ' + result.punishmentType + '</div>';
       
        if (result.totalTime > 0 && !result.hasDClass) {
            html += '<div class="time-result">Время заключения: ' + result.totalTime + ' минут</div>';
        }
       
        if (result.hasDismissal) {
            html += '<div style="color: #f44336; margin-top: 10px;">⚠️ <strong>Обязательное увольнение с текущей должности</strong></div>';
        }
       
        // Дополнительная информация
        html += '<div style="margin-top: 15px; font-size: 12px; color: #666;">';
        html += '<strong>Примечания:</strong><br>';
        html += '• Статьи одной категории (одинаковые последние 2 цифры) не складываются<br>';
        html += '• Статьи разных категорий складываются<br>';
        html += '• При сроке 50+ минут - обязательный перевод в Д-класс<br>';
        html += '• При сроке 35+ минут класс Д может добровольно перейти в Д-класс';
        html += '</div>';
       
        resultDiv.innerHTML = html;
        resultDiv.style.display = 'block';
     }
     }
 
      
     // Инициализация при загрузке страницы
     if (document.readyState === 'loading') {
     if (document.getElementById('law-checkboxes')) {
        document.addEventListener('DOMContentLoaded', init);
         generateLawCheckboxes();
    } else {
         init();
     }
     }
   
})();
});
});

Версия от 10:52, 27 сентября 2025

$(document).ready(function() {
    // Инициализация боковой панели
    $('.боковая-панель-кнопка').on('click', function() {
        var targetId = $(this).data('target');
        
        // Удаляем активный класс у всех кнопок
        $('.боковая-панель-кнопка').removeClass('active');
        // Добавляем активный класс текущей кнопке
        $(this).addClass('active');
        
        // Скрываем все разделы
        $('.боковая-панель-раздел').removeClass('default');
        // Показываем выбранный раздел
        $('#' + targetId).addClass('default');
    });
    
    // Активируем первую кнопку по умолчанию
    $('.боковая-панель-кнопка:first').click();
    
    // Подключаем Tippy.js через CDN динамически
    if (!window.tippy) {
        var tippyScript = document.createElement('script');
        tippyScript.src = "https://unpkg.com/@popperjs/core@2/dist/umd/popper.min.js";
        tippyScript.onload = function() {
            var tippyCoreScript = document.createElement('script');
            tippyCoreScript.src = "https://unpkg.com/tippy.js@6/dist/tippy-bundle.umd.min.js";
            tippyCoreScript.onload = initTippy;
            document.head.appendChild(tippyCoreScript);
        };
        document.head.appendChild(tippyScript);

        // Подключаем CSS
        var tippyCSS = document.createElement('link');
        tippyCSS.rel = "stylesheet";
        tippyCSS.href = "https://unpkg.com/tippy.js@6/dist/tippy.css";
        document.head.appendChild(tippyCSS);
    } else {
        initTippy();
    }

    // Инициализация Tippy после загрузки скриптов
    function initTippy() {
        $('.допуск-контейнер').each(function() {
            var content = $(this).find('.допуск-подсказка').html(); // берем содержимое подсказки
            tippy(this, {
                content: content,
                allowHTML: true,
                interactive: true,
                placement: 'auto',      // автоматический выбор позиции
                maxWidth: '500px',
                minHeight: 'auto',
                theme: 'dark',          // темная тема
                arrow: true,           // без стрелки
                duration: [200, 200],   // плавное появление/исчезание
                popperOptions: {
                    modifiers: [
                        {
                            name: 'preventOverflow',
                            options: {
                                padding: 8 // отступ от краев экрана
                            }
                        },
                        {
                            name: 'flip',
                            options: {
                                fallbackPlacements: ['top', 'bottom', 'right', 'left']
                            }
                        }
                    ]
                }
            });
        });
    }

    // Универсальная система подсказок для таблиц законов
(function() {
    'use strict';
    
    if (window.lawTooltipsLoaded) return;
    window.lawTooltipsLoaded = true;
    
    // Функция загрузки Tippy.js
    function loadTippy(callback) {
        if (window.tippy) {
            callback();
            return;
        }
        
        var popperScript = document.createElement('script');
        popperScript.src = 'https://unpkg.com/@popperjs/core@2/dist/umd/popper.min.js';
        popperScript.onload = function() {
            var tippyScript = document.createElement('script');
            tippyScript.src = 'https://unpkg.com/tippy.js@6/dist/tippy-bundle.umd.min.js';
            tippyScript.onload = callback;
            document.head.appendChild(tippyScript);
        };
        document.head.appendChild(popperScript);
        
        var tippyCSS = document.createElement('link');
        tippyCSS.rel = 'stylesheet';
        tippyCSS.href = 'https://unpkg.com/tippy.js@6/dist/tippy.css';
        document.head.appendChild(tippyCSS);
    }
    
    // Функция извлечения информации из детальных таблиц
    function extractLawDataFromPage() {
        var lawData = {};
        
        // Ищем все таблицы с детальными описаниями
        var detailTables = document.querySelectorAll('.mw-collapsible-content table');
        
        detailTables.forEach(function(table) {
            var rows = table.querySelectorAll('tr');
            
            rows.forEach(function(row) {
                var cells = row.querySelectorAll('td');
                if (cells.length >= 3) {
                    var crimeCell = cells[0];
                    var descriptionCell = cells[1];
                    var exampleCell = cells[2];
                    
                    // Ищем якорь с номером статьи
                    var anchor = crimeCell.querySelector('[id]');
                    if (anchor) {
                        var lawCode = anchor.id;
                        var titleElement = crimeCell.querySelector('b');
                        
                        if (titleElement && lawCode.match(/^\d{3}$/)) {
                            var titleText = titleElement.textContent.trim();
                            var titleParts = titleText.split('\n\n');
                            var lawTitle = titleParts.length > 1 ? titleParts[1] : titleText;
                            
                            var description = descriptionCell.textContent.trim();
                            
                            // Извлекаем примеры из списка
                            var examples = [];
                            var exampleItems = exampleCell.querySelectorAll('li');
                            exampleItems.forEach(function(item) {
                                var text = item.textContent.trim();
                                if (text) {
                                    examples.push(text);
                                }
                            });
                            
                            lawData[lawCode] = {
                                title: lawTitle,
                                description: description,
                                examples: examples
                            };
                        }
                    }
                }
            });
        });
        
        return lawData;
    }
    
    // Функция создания HTML для подсказки
    function createTooltipContent(lawCode, lawData) {
        var data = lawData[lawCode];
        if (!data) return null;
        
        var html = '<div class="law-tooltip">';
        html += '<h4 class="law-tooltip-title">' + lawCode + ' - ' + data.title + '</h4>';
        html += '<p class="law-tooltip-description">' + data.description + '</p>';
        
        if (data.examples && data.examples.length > 0) {
            html += '<div class="law-tooltip-examples">';
            html += '<strong>Примеры:</strong>';
            html += '<ul>';
            data.examples.slice(0, 5).forEach(function(example) { // Ограничиваем до 5 примеров
                html += '<li>' + example + '</li>';
            });
            html += '</ul>';
            html += '</div>';
        }
        html += '</div>';
        
        return html;
    }
    
    // Инициализация подсказок
    function initTooltips() {
        var lawData = extractLawDataFromPage();
        
        // Ищем все ссылки на статьи (и в основной таблице, и в детальных)
        var lawLinks = document.querySelectorAll('a[href*="#"]');
        
        lawLinks.forEach(function(link) {
            var href = link.getAttribute('href');
            var match = href.match(/#(\d{3})/);
            
            if (match) {
                var lawCode = match[1];
                var tooltipContent = createTooltipContent(lawCode, lawData);
                
                if (tooltipContent) {
                    tippy(link, {
                        content: tooltipContent,
                        allowHTML: true,
                        interactive: true,
                        placement: 'auto',
                        maxWidth: 450,
                        theme: 'law-theme',
                        arrow: true,
                        duration: [300, 200],
                        delay: [400, 100],
                        popperOptions: {
                            modifiers: [
                                {
                                    name: 'preventOverflow',
                                    options: {
                                        padding: 10
                                    }
                                },
                                {
                                    name: 'flip',
                                    options: {
                                        fallbackPlacements: ['top', 'bottom', 'right', 'left']
                                    }
                                }
                            ]
                        },
                        onShow: function(instance) {
                            // Скрываем другие открытые подсказки
                            document.querySelectorAll('[data-tippy-root]').forEach(function(tooltip) {
                                if (tooltip._tippy && tooltip._tippy !== instance) {
                                    tooltip._tippy.hide();
                                }
                            });
                        }
                    });
                }
            }
        });
        
        console.log('Загружено подсказок для статей:', Object.keys(lawData).length);
    }
    
    // Запуск после загрузки страницы
    function init() {
        loadTippy(function() {
            // Ждем немного, чтобы все элементы MediaWiki загрузились
            setTimeout(initTooltips, 500);
        });
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
    
	})();
});