document.addEventListener("DOMContentLoaded", function() { // ==================================================================== // --- НАСТРОЙКИ --- // ==================================================================== var tgBotUsername = "Disort_bot"; var consultLink = "https://b24-bcv12q.bitrix24.site/crm_form_fe4rd/"; var baseUrl = "https://disort.ru/myproject/guide/"; var deliveryLink = "https://b24-bcv12q.bitrix24.site/crm_form_kfbk1/"; var consultText = "КОНСУЛЬТАЦИЯ ДИРЕКТОРА"; var calcText = "ПРОВЕРИТЬ В ГИДЕ"; var deliveryText = "БЕСПЛАТНАЯ ДОСТАВКА РФ"; var discountText = "ЗАПРОС СКИДКИ"; var targetSection = "/catalog/napolnye_pokrytiya/pvkh_plitka/"; // --- ЛОГИКА ПРОВЕРКИ СТРАНИЦЫ (ИСПРАВЛЕНО) --- var currentPath = window.location.pathname; // 1. Базовая проверка: находимся ли мы вообще в нужном разделе if (targetSection !== "" && currentPath.indexOf(targetSection) === -1) { return; } // 2. ДОПОЛНИТЕЛЬНАЯ ПРОВЕРКА: Исключаем сам список товаров (каталог) // Нормализуем пути (убираем слеши в конце и начале для сравнения) var cleanCurrentPath = currentPath.replace(/^\/|\/$/g, ''); var cleanTargetSection = targetSection.replace(/^\/|\/$/g, ''); // Если мы находимся ровно в корне раздела — это список, выходим if (cleanCurrentPath === cleanTargetSection) { console.log("Custom Buttons: Catalog list page detected. Skipping insertion."); return; } // 3. Исключаем страницы умного фильтра (обычно содержат /filter/ или /apply/) if (currentPath.indexOf('/filter/') !== -1 || currentPath.indexOf('/apply/') !== -1) { console.log("Custom Buttons: Filter page detected. Skipping insertion."); return; } console.log("Custom Buttons: Product page detected. Initializing Smart Parser..."); // --- ЛОГИКА 1: ПАРСИНГ ДАННЫХ СО СТРАНИЦЫ --- function getPageProductData() { var brand = ''; var collection = ''; try { // Стратегия 1: Поиск по блокам свойств (как в вашем примере) var propItems = document.querySelectorAll('.properties-group__item'); if (propItems.length > 0) { for (var i = 0; i < propItems.length; i++) { var item = propItems[i]; var nameEl = item.querySelector('.properties-group__name'); var valueEl = item.querySelector('.properties-group__value'); if (nameEl && valueEl) { var name = nameEl.innerText.trim().toLowerCase().replace(':', ''); var value = valueEl.innerText.trim(); if (name === 'бренд' || name === 'производитель') brand = value; if (name === 'коллекция') collection = value; } } } // Стратегия 2: Поиск по таблицам (резервный вариант для старых шаблонов) if (!brand || !collection) { var rows = document.querySelectorAll('tr'); for (var k = 0; k < rows.length; k++) { var cells = rows[k].querySelectorAll('td'); if (cells.length >= 2) { var rowName = cells[0].innerText.trim().toLowerCase().replace(':', ''); var rowValue = cells[1].innerText.trim(); if (!brand && (rowName === 'бренд' || rowName === 'производитель')) brand = rowValue; if (!collection && (rowName === 'коллекция')) collection = rowValue; } } } } catch (e) { console.error("Error parsing product properties:", e); } console.log("Parsed from page -> Brand:", brand, "Collection:", collection); return { brand: brand, collection: collection }; } // --- ЛОГИКА 2: ГЕНЕРАЦИЯ ССЫЛКИ НА ГИД --- function getGuideLink(data) { var params = []; // Если данные не переданы, пробуем получить их сейчас var productData = data || getPageProductData(); if (productData.brand) params.push("context_brand=" + encodeURIComponent(productData.brand)); if (productData.collection) params.push("context_collection=" + encodeURIComponent(productData.collection)); // Fallback: если ничего не нашли, берем из URL if (params.length === 0) { var path = window.location.pathname.replace(/^\/|\/$/g, ''); var parts = path.split('/'); var slug = parts[parts.length - 1]; if(slug) params.push("search_1=" + encodeURIComponent(slug)); } return baseUrl + (params.length ? "?" + params.join("&") : ""); } // Ссылка для ТГ function getSmartTgLink() { var path = window.location.pathname.replace(/^\/|\/$/g, ''); var parts = path.split('/'); var slug = parts[parts.length - 1] || 'item'; return "https://t.me/" + tgBotUsername + "?start=discount_" + slug.replace(/[^a-zA-Z0-9_]/g, ''); } // --- ЛОГИКА ВСТАВКИ (С ОЖИДАНИЕМ) --- function insertButtons() { // Проверяем, вставлены ли уже кнопки if (document.querySelector('.custom-buy-buttons-wrapper')) return; var selectorsToTry = [ '.buy_block .buttons', '.offer_buy_block .counter_wrapp', '.buy_block .counter_wrapp', '.cost.prices', '.middle_info_wrap .buy_block', '.item-stock .store_view' ]; var targetElement = null; for (var i = 0; i < selectorsToTry.length; i++) { var element = document.querySelector(selectorsToTry[i]); if (element) { targetElement = element; break; } } // Если не нашли место для вставки ИЛИ не нашли данные товара -> пробуем позже var productData = getPageProductData(); // Вставляем, если нашли место (даже если данные товара не полные, ссылка сгенерируется с fallback) if (targetElement) { var wrapper = document.createElement('div'); wrapper.className = 'custom-buy-buttons-wrapper'; // СТИЛИ ВРАППЕРА: Flex Wrap + Box Sizing wrapper.style.cssText = 'margin: 15px 0 25px 0; width: 100%; max-width: 100%; display: flex; flex-wrap: wrap !important; gap: 8px; box-sizing: border-box;'; // Генерируем ссылку ПРЯМО ПЕРЕД ВСТАВКОЙ, чтобы захватить данные, если они появились var finalCalcLink = getGuideLink(productData); var smartDiscountLink = getSmartTgLink(); function makeBtn(link, text, iconClass, bgColor, hoverColor, shadowColor) { var btn = document.createElement('a'); btn.href = link; btn.target = "_blank"; btn.className = 'btn'; // СТИЛИ КНОПКИ: White-space normal (перенос текста), calc(50% - 8px) для сетки 2x2 btn.style.cssText = "display: flex; align-items: center; justify-content: center; flex: 1 1 calc(50% - 8px); padding: 10px 4px; border-radius: 4px; font-weight: 700; text-decoration: none; cursor: pointer; transition: 0.3s; text-transform: uppercase; font-size: 10px; line-height: 1.1; border: none; min-width: 100px; color: #fff; background: " + bgColor + "; box-shadow: 0 2px 5px " + shadowColor + "; white-space: normal !important; box-sizing: border-box;"; btn.innerHTML = '' + text + ''; btn.onmouseover = function(){ this.style.background = hoverColor; this.style.textDecoration = 'none'; }; btn.onmouseout = function(){ this.style.background = bgColor; }; return btn; } wrapper.appendChild(makeBtn(finalCalcLink, calcText, "fa-calculator", "#28a745", "#218838", "rgba(40,167,69,0.3)")); wrapper.appendChild(makeBtn(consultLink, consultText, "fa-commenting-o", "#0056b3", "#004494", "rgba(0,86,179,0.3)")); wrapper.appendChild(makeBtn(deliveryLink, deliveryText, "fa-truck", "#17a2b8", "#117a8b", "rgba(23,162,184,0.3)")); wrapper.appendChild(makeBtn(smartDiscountLink, discountText, "fa-percent", "#33b5e5", "#1ba1d1", "rgba(51,181,229,0.3)")); targetElement.parentNode.insertBefore(wrapper, targetElement.nextSibling); console.log("Custom Buttons: Inserted successfully."); return true; // Успех } return false; // Не нашли место } // Попытка вставки с повторениями (Retry Logic) var attempts = 0; var maxAttempts = 10; function tryInsert() { attempts++; var success = insertButtons(); if (!success && attempts < maxAttempts) { console.log("Custom Buttons: Attempt " + attempts + " failed. Retrying in 500ms..."); setTimeout(tryInsert, 500); } else if (!success) { // Если не нашли основные селекторы, пробуем вставить в правую колонку как last resort var rightCol = document.querySelector('.right_info_block'); if (rightCol && !document.querySelector('.custom-buy-buttons-wrapper')) { // Логируем неудачу console.log("Custom Buttons: Could not find target selector after " + maxAttempts + " attempts."); } } } tryInsert(); });