Jamil-Abdullayev b8246597d4 Initial commit: orgsteklo WordPress theme
Custom WooCommerce theme for orgsteklo.ru including:
- Product catalog with category/subcategory hierarchy
- Custom checkout with delivery calculation
- Price calculator
- Admin settings panel
- Search functionality
- User account pages
2026-03-05 00:48:06 +04:00

1692 lines
59 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// --- SAFE GLOBAL FALLBACK: updateQuantity ---
// Объявляем глобально и раньше любых обработчиков, чтобы не было ReferenceError.
(function ($, w, d) {
if (typeof w.updateQuantity !== 'function') {
w.updateQuantity = function (productId, quantity) {
var ajaxUrl = (w.wc_add_to_cart_params && wc_add_to_cart_params.ajax_url)
? wc_add_to_cart_params.ajax_url
: '/wp-admin/admin-ajax.php';
return $.ajax({
url: ajaxUrl,
type: 'POST',
data: {
action: 'update_cart_quantity',
product_id: productId,
quantity: quantity
}
}).done(function (response) {
// Если Woo отдал фрагменты — обновим их
if (response && response.fragments) {
$.each(response.fragments, function (key, value) {
try { $(key).replaceWith(value); } catch (e) {}
});
}
// Перерисуем мини-корзину/счётчик, если есть
if (typeof w.updateCartButtons === 'function') {
try { w.updateCartButtons(); } catch (e) {}
}
// Триггер Woo
try { $(d.body).trigger('wc_fragment_refresh'); } catch (e) {}
}).fail(function (xhr, status, error) {
console.error('Ошибка AJAX при updateQuantity:', error || status);
});
};
}
})(jQuery, window, document);
// --- /SAFE GLOBAL FALLBACK ---
$(document).ready(function() {
$('.phone').inputmask('+7 999 999 99 99');
});
$(document).ready(function() {
$.fancybox.defaults.hideScrollbar = false;
$.fancybox.defaults.animationEffect = "fade";
$.fancybox.defaults.animationDuration = 600;
$('[data-fancybox]').fancybox();
});
function toggleMenu($button) {
var $menu = $('.pc_menu');
var $menu_fon = $('.pc_menu__fon');
var $body = $('body');
$button.toggleClass('change');
$menu.toggleClass('active');
$menu_fon.toggleClass('active');
if ($menu.hasClass('active')) {
$body.addClass('hidden');
$menu_fon.addClass('active');
} else {
$body.removeClass('hidden');
$menu_fon.removeClass('active');
}
}
$('.header-catalog__button').on('click', function () {
toggleMenu($(this));
});
$('.pc_menu__fon').on('click', function () {
if ($('.pc_menu').hasClass('active')) {
toggleMenu($('.header-catalog__button'));
}
});
$('.pc_menu nav a').on('click', function () {
if ($('.pc_menu').hasClass('active')) {
toggleMenu($('.header-catalog__button'));
}
});
function toggleMenu2($button) {
var $menu = $('.menu_mob');
var $menu_fon = $('.menu_mob-close');
var $body = $('body');
$button.toggleClass('change');
$menu.toggleClass('active');
$menu_fon.toggleClass('active');
if ($menu.hasClass('active')) {
$body.addClass('hidden');
$menu_fon.addClass('active');
} else {
$body.removeClass('hidden');
$menu_fon.removeClass('active');
}
}
$('.header-catalog__button-mob').on('click', function () {
toggleMenu2($(this));
});
$('.menu_mob-close').on('click', function () {
if ($('.menu_mob').hasClass('active')) {
toggleMenu2($('.header-catalog__button-mob'));
}
});
$(document).ready(function () {
$('.catalog_page-menu__item').each(function () {
const dropdown = $(this);
const dropdownName = dropdown.find('.catalog_page-menu__item-button__icon');
const dropdownContent = dropdown.find('.catalog_page-menu__item-content');
dropdownName.on('click', function () {
if (!dropdown.hasClass('all-list')) {
dropdown.toggleClass('active');
if (dropdown.hasClass('active')) {
dropdownContent.css('max-height', dropdownContent.prop('scrollHeight') + 'px');
}
else {
dropdownContent.css('max-height', '');
}
}
});
});
});
$(document).ready(function () {
$('.catalog_page-menu__item-content-item').each(function () {
const dropdown = $(this);
const dropdownName = dropdown.find('.catalog_page-menu__item-content-item-icon');
const dropdownContent = dropdown.find('.catalog_page-menu__item-content-item-content');
dropdownName.on('click', function () {
if (!dropdown.hasClass('all-list')) {
dropdown.toggleClass('active');
if (dropdown.hasClass('active')) {
dropdownContent.css('max-height', dropdownContent.prop('scrollHeight') + 'px');
}
else {
dropdownContent.css('max-height', '');
}
}
});
});
});
// Переключатель вида каталога (компактный / расширенный)
$(document).ready(function() {
var grid = $('.catalog_page-products__grid');
var viewBtns = $('.catalog_page-view-btn');
if (grid.length && viewBtns.length) {
var savedView = localStorage.getItem('catalog_view') || 'extended';
grid.addClass('view-' + savedView);
viewBtns.each(function() {
if ($(this).data('view') === savedView) {
$(this).addClass('active');
}
});
viewBtns.on('click', function() {
var view = $(this).data('view');
grid.removeClass('view-compact view-extended').addClass('view-' + view);
viewBtns.removeClass('active');
$(this).addClass('active');
localStorage.setItem('catalog_view', view);
});
}
});
$(document).ready(function() {
$('.catalog_page-count__button').on('click', function() {
$(this).toggleClass('active');
$('.catalog_page-count__content').toggleClass('active');
});
$('.catalog_page-count__content-button').on('click', function() {
var selectedText = $(this).find('p').text().trim();
var perPage = selectedText === 'Все' ? 'all' : parseInt(selectedText);
var url = new URL(window.location.href);
url.searchParams.set('per_page', perPage);
url.searchParams.delete('paged'); // сбрасываем на первую страницу
// Удаляем /page/N/ из URL
url.pathname = url.pathname.replace(/\/page\/\d+\/?/, '/');
window.location.href = url.toString();
});
});
$(document).ready(function () {
$(".documentation-tab").click(function () {
$(".documentation-tab").removeClass("active");
$(".documentation-content").removeClass("active");
$(this).addClass("active");
var index = $(this).index();
$(".documentation-content:eq(" + index + ")").addClass("active");
});
});
$(document).ready(function() {
$('.documentation-mob__button').on('click', function() {
$(this).toggleClass('active');
$('.documentation-mob__content').toggleClass('active');
});
$('.documentation-mob__item').on('click', function() {
$('.documentation-mob__item').removeClass('active');
$(this).addClass('active');
$('.documentation-mob__content, .documentation-mob__button').removeClass('active');
const selectedText = $(this).find('p').text();
$('.documentation-mob__button p').text(selectedText);
});
});
$(document).ready(function () {
$(".documentation-mob__item").click(function () {
$(".documentation-mob__item").removeClass("active");
$(".documentation-content").removeClass("active");
$(this).addClass("active");
var index = $(this).index();
$(".documentation-content:eq(" + index + ")").addClass("active");
});
});
$(document).ready(function () {
$(".registration-tab").click(function () {
$(".registration-tab").removeClass("active");
$(".registration-content").removeClass("active");
$(this).addClass("active");
var index = $(this).index();
$(".registration-content:eq(" + index + ")").addClass("active");
});
});
$(document).ready(function() {
$('.popup-registration__open').on('click', function() {
$('.popup-registration').css('display', 'flex');
});
$('.popup-registration__close, .popup-registration__fon').on('click', function() {
$('.popup-registration').css('display', 'none');
});
});
$(document).ready(function() {
$('.popup-callback__open').on('click', function() {
$('.popup-callback').css('display', 'flex');
});
$('.popup-callback__close, .popup-callback__fon').on('click', function() {
$('.popup-callback').css('display', 'none');
});
});
$(document).ready(function () {
$(".product_page-tab").click(function () {
$(".product_page-tab").removeClass("active");
$(".product_page-content").removeClass("active");
$(this).addClass("active");
var index = $(this).index();
$(".product_page-content:eq(" + index + ")").addClass("active");
});
});
$(document).ready(function() {
$('.product_page-tabs__mob-button').on('click', function() {
$(this).toggleClass('active');
$('.product_page-tabs__mob-content').toggleClass('active');
});
$('.product_page-tabs__mob-tab').on('click', function() {
$('.product_page-tabs__mob-tab').removeClass('active');
$(this).addClass('active');
$('.product_page-tabs__mob-content, .product_page-tabs__mob-button').removeClass('active');
const selectedText = $(this).find('p').text();
$('.product_page-tabs__mob-button p').text(selectedText);
});
});
$(document).ready(function () {
$(".product_page-tabs__mob-tab").click(function () {
$(".product_page-tabs__mob-tab").removeClass("active");
$(".product_page-content").removeClass("active");
$(this).addClass("active");
var index = $(this).index();
$(".product_page-content:eq(" + index + ")").addClass("active");
});
});
$(document).ready(function() {
$('.popup-cart__open').on('click', function() {
$('.popup-cart').css('display', 'flex');
});
$('.popup-cart__close, .popup-cart__fon').on('click', function() {
$('.popup-cart').css('display', 'none');
});
});
$(document).ready(function() {
$('.popup-cart-product__open').on('click', function() {
$('.popup-cart-product').css('display', 'flex');
});
$('.popup-cart-product__close, .popup-cart-product__fon').on('click', function() {
$('.popup-cart-product').css('display', 'none');
});
});
$(document).ready(function () {
// Функция автозаполнения полей из профиля
function fillCheckoutFields(tabIndex) {
if (typeof orgstekloCheckoutUser === 'undefined' || !orgstekloCheckoutUser.isLoggedIn) return;
var u = orgstekloCheckoutUser;
if (tabIndex === 0) {
$('#billing_fio').val(u.fio || '');
$('#billing_phone_phys').val(u.phone || '');
$('#billing_email_phys').val(u.email || '');
} else if (tabIndex === 1) {
$('#billing_company_name').val(u.company_name || '');
$('#billing_inn').val(u.inn || '');
$('#billing_kpp').val(u.kpp || '');
$('#billing_legal_address').val(u.legal_address || '');
$('#billing_actual_address').val(u.actual_address || '');
$('#billing_contact_person').val(u.fio || '');
$('#billing_phone_legal').val(u.phone || '');
$('#billing_email_legal').val(u.email || '');
}
}
$(".checkout-data__tab").click(function () {
$(".checkout-data__tab").removeClass("active");
$(".checkout-data__content").removeClass("active");
$(this).addClass("active");
var index = $(this).index();
$(".checkout-data__content").eq(index).addClass("active");
// Проверка на авторизацию
var isLoggedIn = $('body').hasClass('logged-in');
if (index === 1 && !isLoggedIn) {
// Блокировка кнопки
$("#place_order").prop("disabled", true);
// Скрыть consult-checkbox, показать checkout-description
$(".consult-checkbox").hide();
$(".checkout-description").show();
} else {
// Разблокировать кнопку
$("#place_order").prop("disabled", false);
// Показать consult-checkbox, скрыть checkout-description
$(".consult-checkbox").show();
$(".checkout-description").hide();
}
// Автозаполнение полей
fillCheckoutFields(index);
// Обновить видимость способов оплаты
if (typeof updatePaymentMethodVisibility === 'function') {
updatePaymentMethodVisibility();
}
});
// Автозаполнение при загрузке страницы (активный таб по умолчанию)
fillCheckoutFields($(".checkout-data__tab.active").index());
});
$(document).ready(function() {
$('.lk-menu__mobile-button').on('click', function() {
$(this).toggleClass('active');
$('.lk-menu__mobile-content').toggleClass('active');
});
$('.lk-menu__mobile-content__link').on('click', function() {
$('.lk-menu__mobile-content__link').removeClass('active');
$(this).addClass('active');
$('.lk-menu__mobile-content, .lk-menu__mobile-button').removeClass('active');
const selectedText = $(this).find('p').text();
$('.lk-menu__mobile-button p').text(selectedText);
});
});
$(document).ready(function() {
$('.popup-password_change__open').on('click', function() {
$('.popup-password_change').css('display', 'flex');
});
$('.popup-password_change__close, .popup-password_change__fon').on('click', function() {
$('.popup-password_change').css('display', 'none');
});
});
$(document).ready(function() {
$('.popup-email_change__open').on('click', function() {
$('.popup-email_change').css('display', 'flex');
});
$('.popup-email_change__close, .popup-email_change__fon').on('click', function() {
$('.popup-email_change').css('display', 'none');
});
});
$(document).ready(function() {
$('.popup-delete_acc__open').on('click', function() {
$('.popup-delete_acc').css('display', 'flex');
});
$('.popup-delete_acc__close, .popup-delete_acc__fon').on('click', function() {
$('.popup-delete_acc').css('display', 'none');
});
});
$(document).ready(function() {
function openMinicart() {
$('.minicart__fon').css('display', 'flex');
$('.minicart').css('display', 'flex');
$('body').css('overflow', 'hidden');
}
function closeMinicart() {
$('.minicart__fon').css('display', 'none');
$('.minicart').css('display', 'none');
$('body').css('overflow', 'auto');
}
$('.minicart-open').on('click mouseenter', openMinicart);
$('.minicart__fon').on('click', closeMinicart);
// Закрытие при уходе курсора с .minicart и .minicart-open
let minicartHover = false;
$('.minicart, .minicart-open').on('mouseenter', function() {
minicartHover = true;
});
$('.minicart, .minicart-open').on('mouseleave', function() {
minicartHover = false;
setTimeout(function() {
if (!minicartHover) {
closeMinicart();
}
}, 500); // задержка нужна, чтобы не срабатывало при переходе между элементами
});
});
$(document).ready(function() {
const $menuColumns = $('.menu_mob-column, .menu_mob-logo');
const $menuContents = $('.menu_mob-menu__content');
$menuContents.hide();
$('.menu_mob-menu__button').on('click', function() {
$menuContents.hide();
const contentId = $(this).data('content');
$menuColumns.hide();
$menuContents.filter('[data-content="' + contentId + '"]').show();
});
$('.menu_mob-menu__content-back').on('click', function() {
$menuContents.hide();
$(this).closest('.menu_mob-menu__content').hide();
$menuColumns.show();
});
});
jQuery(document).ready(function($) {
$('.projects-more_page').on('click', function() {
const hiddenItems = $('.projects-item.hidden');
hiddenItems.slice(0, 6).removeClass('hidden');
if ($('.projects-item.hidden').length === 0) {
$(this).hide();
}
});
});
jQuery(document).ready(function($) {
$('.documentation-more').on('click', function() {
const $container = $(this).closest('.documentation-content');
$container.find('.documentation-item.hidden').removeClass('hidden');
$(this).hide();
});
});
//login
jQuery(document).ready(function($) {
$('#login-form').on('submit', function(e) {
e.preventDefault();
const phone = $('#login-form input[type=tel]').val();
const password = $('#login-form #login-password').val();
$.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: {
action: 'login_by_phone',
phone: phone,
password: password
},
success: function(response) {
if (response.success) {
window.location.href = '/account';
}
else {
$('.login-error').show();
}
}
});
});
});
jQuery(document).ready(function($) {
$('.login-password__button').on('click', function() {
const $button = $(this);
const $container = $button.closest('.login-form__input');
const $input = $container.find('input');
const $img = $button.find('img');
if ($input.attr('type') === 'password') {
$input.attr('type', 'text');
$img.attr('src', '/wp-content/uploads/2025/05/password.svg');
} else {
$input.attr('type', 'password');
$img.attr('src', '/wp-content/uploads/2025/05/password-2.svg');
}
});
});
jQuery(document).ready(function($) {
$('#recovery-form').on('submit', function(e) {
e.preventDefault();
const email = $(this).find('input[name="user_email"]').val();
$.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: {
action: 'custom_password_reset',
user_email: email
},
success: function(response) {
if (response.success) {
window.location.href = '/password-sent';
} else {
$('.login-error').fadeIn();
}
}
});
});
});
jQuery(document).ready(function($) {
$('#home_categories_more').on('click', function(e) {
e.preventDefault();
$('.categories-item.hidden').slideDown().removeClass('hidden');
$(this).remove();
});
});
jQuery(document).ready(function($) {
let verificationCode = '';
let timerInterval;
function startTimer($timerElement, $resendButton) {
let timeLeft = 120;
$timerElement.show();
$resendButton.hide();
timerInterval = setInterval(function () {
timeLeft--;
const minutes = String(Math.floor(timeLeft / 60)).padStart(2, '0');
const seconds = String(timeLeft % 60).padStart(2, '0');
$timerElement.text(`Отправить код повторно через ${minutes}:${seconds}`);
if (timeLeft <= 0) {
clearInterval(timerInterval);
$timerElement.hide();
$resendButton.show();
}
}, 1000);
}
function sendSMS(phone, callback) {
$.ajax({
url: '/wp-admin/admin-ajax.php',
method: 'POST',
data: {
action: 'send_sms_code',
phone: phone
},
success: function(response) {
if (response.success) {
verificationCode = response.data.code;
callback();
} else {
alert(response.data.message || 'Ошибка отправки SMS');
}
}
});
}
$('.registration-form').on('submit', function(e) {
e.preventDefault();
const $form = $(this);
const email = $form.find('input[type=email]').val();
const phone = $form.find('input[type=tel]').val();
const password = $form.find('input[type=password]').val();
const registration_type = $form.find('input[name=registration_type]').val();
const checkbox = $form.find('input[name="login-form__remember"]');
if (!checkbox.is(':checked')) {
alert('Подтвердите согласие с политикой конфиденциальности');
return;
}
$.ajax({
url: '/wp-admin/admin-ajax.php',
method: 'POST',
data: {
action: 'check_email_exists',
email: email
},
success: function(response) {
if (response.exists) {
$('.login-error').css('display', 'flex');
} else {
sendSMS(phone, function() {
$('.popup-registration').css('display', 'flex');
$('.popup-registration__name b').text(phone);
startTimer($('.popup-registration p:contains("через")'), $('.popup-registration__code-button'));
$('.popup-registration__submit').off('click').on('click', function(e) {
e.preventDefault();
const enteredCode = $('.popup-registration__input input').val();
$.ajax({
url: '/wp-admin/admin-ajax.php',
method: 'POST',
data: {
action: 'register_user',
email: email,
password: password,
phone: phone,
registration_type: registration_type,
code: enteredCode
},
success: function(res) {
if (res.success) {
window.location.href = '/registration-success';
} else {
alert(res.data.message);
}
}
});
});
});
}
}
});
});
$('.popup-registration__code-button').on('click', function(e) {
e.preventDefault();
const phone = $('.popup-registration__name b').text();
sendSMS(phone, function() {
startTimer($('.popup-registration p:contains("через")'), $('.popup-registration__code-button'));
});
});
});
jQuery(document).ready(function ($) {
$('.popup-delete_acc-yes').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'delete_my_account'
},
success: function () {
window.location.href = '/'; // редирект после удаления
},
error: function () {
console.error('Ошибка при удалении аккаунта.');
}
});
});
});
jQuery(document).ready(function ($) {
// Сохранение формы профиля
$('.profile-individual').on('submit', function (e) {
e.preventDefault();
const name = $('.profile input[placeholder="ФИО*"]').val();
const phone = $('.profile input[type="tel"]').val();
const email = $('.profile input[type="email"]').val();
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'save_user_profile_data',
name: name,
phone: phone,
email: email
},
success: function (response) {
if (response.success) {
alert('Данные сохранены');
} else {
alert('Ошибка: ' + response.data.message);
}
},
});
});
});
jQuery(document).ready(function ($) {
// Сохранение формы профиля
$('.profile-legal').on('submit', function (e) {
e.preventDefault();
const name = $('.profile input[placeholder="ФИО*"]').val();
const phone = $('.profile input[type="tel"]').val();
const email = $('.profile input[type="email"]').val();
const company_name = $('.profile input[placeholder="Наименование организации*"]').val();
const inn = $('.profile input[placeholder="ИНН*"]').val();
const kpp = $('.profile input[placeholder="КПП"]').val();
const legal_address = $('.profile input[placeholder="Юридический адрес*"]').val();
const actual_address = $('.profile input[placeholder="Фактический адрес*"]').val();
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'save_user_profile_data2',
name: name,
phone: phone,
email: email,
company_name: company_name, // <-- Добавлено
inn: inn, // <-- Добавлено
kpp: kpp, // <-- Добавлено
legal_address: legal_address, // <-- Добавлено
actual_address: actual_address
},
success: function(response) {
if (response.success) {
alert('Данные сохранены');
}
},
});
});
});
jQuery(document).ready(function ($) {
$('#send-verification-email').on('click', function () {
$.post('/wp-admin/admin-ajax.php', {
action: 'send_email_verification_link'
}, function (res) {
if (res.success) {
$('.popup-email_change').css('display', 'flex');
} else {
alert('Ошибка: ' + res.data.message);
}
});
});
});
jQuery(document).ready(function ($) {
const $changeBtn = $('.profile-password__change');
const $currentPassBlock = $('.profile-password__col');
const $currentPassInput = $('.profile-password__col .individual_old_input');
const $newPassBlock = $('.profile-password__col-new');
const $saveNewPassBtn = $('.profile-password__new-submit');
const $popup = $('.popup-password_change');
$changeBtn.on('click', function () {
const currentPassword = $currentPassInput.val();
if (currentPassword.length < 6) {
alert('Введите текущий пароль (не менее 6 символов)');
return;
}
$.post('/wp-admin/admin-ajax.php', {
action: 'check_user_password',
password: currentPassword
}, function (response) {
if (response.success) {
$changeBtn.hide();
$currentPassBlock.hide();
$newPassBlock.show();
} else {
alert('Неверный текущий пароль');
}
});
});
$saveNewPassBtn.on('click', function () {
const oldPass = $newPassBlock.find('input[placeholder="Старый пароль"]').val();
const newPass = $newPassBlock.find('input[placeholder="Новый пароль"]').val();
if (newPass.length < 6) {
alert('Новый пароль должен быть не менее 6 символов');
return;
}
$.post('/wp-admin/admin-ajax.php', {
action: 'change_user_password',
old_password: oldPass,
new_password: newPass
}, function (response) {
if (response.success) {
$popup.css('display', 'flex');
} else {
alert(response.message || 'Ошибка при смене пароля');
}
});
});
});
jQuery(document).ready(function($) {
$('.profile-password__button').on('click', function() {
const $button = $(this);
const $container = $button.closest('.profile-input');
const $input = $container.find('input');
const $img = $button.find('img');
if ($input.attr('type') === 'password') {
$input.attr('type', 'text');
$img.attr('src', '/wp-content/uploads/2025/05/password.svg');
} else {
$input.attr('type', 'password');
$img.attr('src', '/wp-content/uploads/2025/05/password-2.svg');
}
});
});
jQuery(document).ready(function($) {
$('form.product_page-kley').on('show_variation', function(event, variation) {
const priceHtml = variation.price_html;
const $temp = $('<div>').html(priceHtml);
const newPrice = $temp.find('ins .amount').html() || $temp.find('.amount').html();
const oldPrice = $temp.find('del .amount').html();
let newHtml = '';
if (newPrice) {
newHtml += '<p class="product_page-calc__one-price">' + newPrice + '</p>';
}
if (oldPrice) {
newHtml += '<p class="product_page-calc__one-oldprice">' + oldPrice + '</p>';
}
$('.product_page-calc__one-row').html(newHtml);
});
});
jQuery(document).ready(function($) {
$('form.product_page-trubi').on('show_variation', function(event, variation) {
const priceHtml = variation.price_html;
const $temp = $('<div>').html(priceHtml);
const newPrice = $temp.find('ins .amount').html() || $temp.find('.amount').html();
const oldPrice = $temp.find('del .amount').html();
let newHtml = '';
if (newPrice) {
newHtml += '<p class="product_page-calc__one-price">' + newPrice + '</p>';
}
if (oldPrice) {
newHtml += '<p class="product_page-calc__one-oldprice">' + oldPrice + '</p>';
}
$('.product_page-calc__one-row').html(newHtml);
});
});
jQuery(document).ready(function($) {
$('form.product_page-sterjni').on('show_variation', function(event, variation) {
const priceHtml = variation.price_html;
const $temp = $('<div>').html(priceHtml);
const newPrice = $temp.find('ins .amount').html() || $temp.find('.amount').html();
const oldPrice = $temp.find('del .amount').html();
let newHtml = '';
if (newPrice) {
newHtml += '<p class="product_page-calc__one-price">' + newPrice + '</p>';
}
if (oldPrice) {
newHtml += '<p class="product_page-calc__one-oldprice">' + oldPrice + '</p>';
}
$('.product_page-calc__one-row').html(newHtml);
});
});
jQuery(document).ready(function($) {
const priceHtml = $('.summary .price').html();
const $temp = $('<div>').html(priceHtml);
const newPrice = $temp.find('ins .amount').html() || $temp.find('.amount').html();
const oldPrice = $temp.find('del .amount').html();
let newHtml = '';
if (newPrice) {
newHtml += '<p class="product_page-calc__one-price">' + newPrice + '</p>';
}
if (oldPrice) {
newHtml += '<p class="product_page-calc__one-oldprice">' + oldPrice + '</p>';
}
$('.product_page-calc__one-row').html(newHtml);
});
jQuery(function ($) {
const $form = $('form.product_page-kley');
function updateTotals(variation, qty) {
if (!variation) return;
const weight = parseFloat(variation.weight) || 0;
const totalWeight = (weight * qty).toFixed(3);
$('.product_page-weight p:last-child').text(totalWeight + ' кг');
// Используем raw_price - точная цена как в корзине (get_price())
const newPrice = parseFloat(variation.raw_price) || parseFloat(variation.display_price) || 0;
const oldPrice = parseFloat(variation.raw_regular_price) || parseFloat(variation.display_regular_price) || 0;
// Считаем как корзина: цена * кол-во, потом округление
const totalNew = Math.round(newPrice * qty).toLocaleString('ru-RU');
const totalOld = Math.round(oldPrice * qty).toLocaleString('ru-RU');
$('.product_page-price').html(totalNew + ' <span>₽</span>');
if (oldPrice && oldPrice > newPrice) {
$('.product_page-oldprice').show().html(totalOld + ' <span>₽</span>');
} else {
$('.product_page-oldprice').hide();
}
}
$form.on('show_variation', function (event, variation) {
const qty = parseInt($('.qty').val(), 10) || 1;
updateTotals(variation, qty);
});
$('body').on('input change', '.qty', function () {
const variationID = $('.variation_id').val();
const variations = $form.data('product_variations') || [];
const variation = variations.find(v => v.variation_id == variationID);
if (variation) {
const qty = parseInt($(this).val(), 10) || 1;
updateTotals(variation, qty);
}
});
});
jQuery(function ($) {
const $form = $('form.product_page-trubi');
function updateTotals(variation, qty) {
if (!variation) return;
const weight = parseFloat(variation.weight) || 0;
const totalWeight = (weight * qty).toFixed(3);
$('.product_page-weight p:last-child').text(totalWeight + ' кг');
// Используем raw_price - точная цена как в корзине (get_price())
const newPrice = parseFloat(variation.raw_price) || parseFloat(variation.display_price) || 0;
const oldPrice = parseFloat(variation.raw_regular_price) || parseFloat(variation.display_regular_price) || 0;
// Считаем как корзина: цена * кол-во, потом округление
const totalNew = Math.round(newPrice * qty).toLocaleString('ru-RU');
const totalOld = Math.round(oldPrice * qty).toLocaleString('ru-RU');
$('.product_page-price').html(totalNew + ' <span>₽</span>');
if (oldPrice && oldPrice > newPrice) {
$('.product_page-oldprice').show().html(totalOld + ' <span>₽</span>');
} else {
$('.product_page-oldprice').hide();
}
}
$form.on('show_variation', function (event, variation) {
const qty = parseInt($('.qty').val(), 10) || 1;
updateTotals(variation, qty);
});
$('body').on('input change', '.qty', function () {
const variationID = $('.variation_id').val();
const variations = $form.data('product_variations') || [];
const variation = variations.find(v => v.variation_id == variationID);
if (variation) {
const qty = parseInt($(this).val(), 10) || 1;
updateTotals(variation, qty);
}
});
});
jQuery(function ($) {
const $form = $('form.product_page-sterjni');
function updateTotals(variation, qty) {
if (!variation) return;
const weight = parseFloat(variation.weight) || 0;
const totalWeight = (weight * qty).toFixed(3);
$('.product_page-weight p:last-child').text(totalWeight + ' кг');
// Используем raw_price - точная цена как в корзине (get_price())
const newPrice = parseFloat(variation.raw_price) || parseFloat(variation.display_price) || 0;
const oldPrice = parseFloat(variation.raw_regular_price) || parseFloat(variation.display_regular_price) || 0;
// Считаем как корзина: цена * кол-во, потом округление
const totalNew = Math.round(newPrice * qty).toLocaleString('ru-RU');
const totalOld = Math.round(oldPrice * qty).toLocaleString('ru-RU');
$('.product_page-price').html(totalNew + ' <span>₽</span>');
if (oldPrice && oldPrice > newPrice) {
$('.product_page-oldprice').show().html(totalOld + ' <span>₽</span>');
} else {
$('.product_page-oldprice').hide();
}
}
$form.on('show_variation', function (event, variation) {
const qty = parseInt($('.qty').val(), 10) || 1;
updateTotals(variation, qty);
});
$('body').on('input change', '.qty', function () {
const variationID = $('.variation_id').val();
const variations = $form.data('product_variations') || [];
const variation = variations.find(v => v.variation_id == variationID);
if (variation) {
const qty = parseInt($(this).val(), 10) || 1;
updateTotals(variation, qty);
}
});
});
jQuery(function ($) {
// Работает только на простом товаре
if (!$('form.product_page-simple').length) {
return;
}
function parsePrice(text) {
// Сначала заменяем запятую на точку (десятичный разделитель в RU)
// Потом удаляем пробелы и символ валюты
return parseFloat(text.replace(',', '.').replace(/\s|₽/g, '')) || 0;
}
function updateTotals() {
const qty = parseInt($('.qty').val(), 10) || 1;
// Приоритет: используем скрытые элементы с чистыми ценами (если есть)
// Это гарантирует точное совпадение с серверным расчётом
let newPrice = parseFloat($('.simple-price').data('price')) || 0;
let oldPrice = parseFloat($('.simple-price').data('regular-price')) || 0;
// Fallback: парсим из .price HTML если скрытые элементы не найдены
if (!newPrice) {
const priceHtml = $('.price').html() || '';
const $temp = $('<div>').html(priceHtml);
const newPriceRaw = $temp.find('ins .amount').text() || $temp.find('.amount').first().text();
const oldPriceRaw = $temp.find('del .amount').text();
newPrice = parsePrice(newPriceRaw);
oldPrice = parsePrice(oldPriceRaw);
}
// Округляем итог чтобы совпадало с расчётом корзины
const totalNew = Math.round(newPrice * qty).toLocaleString('ru-RU');
const totalOld = Math.round(oldPrice * qty).toLocaleString('ru-RU');
$('.product_page-price').html(totalNew + ' <span>₽</span>');
if (oldPrice && oldPrice > newPrice) {
$('.product_page-oldprice').show().html(totalOld + ' <span>₽</span>');
} else {
$('.product_page-oldprice').hide();
}
// ✅ Вес для простого товара (.simple-weight) — всегда 3 знака после запятой
const weight = parseFloat(($('.simple-weight').text() || '').replace(',', '.')) || 0;
const totalWeight = (weight * qty).toFixed(3);
$('.product_page-weight p:last-child').text(totalWeight + ' кг');
}
// Обновить при загрузке и при изменении количества
updateTotals();
$('body').on('input change', '.qty', function () {
updateTotals();
});
});
jQuery(function($) {
function updateCartButtons() {
$.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'get_cart_contents'
},
success: function(response) {
console.log('Cart contents:', response);
if (!Array.isArray(response.items)) {
console.error('Invalid response format:', response);
return;
}
updateMiniCart(response.items);
updateTotalPrice(response.total, response.oldTotal);
updateCartCount(response.count);
}
});
}
// Делаем функцию глобальной для доступа из других скриптов
window.updateCartButtons = updateCartButtons;
function updateMiniCart(items) {
var miniCart = $('.minicart-products');
miniCart.empty();
items.forEach(item => {
var oldPriceHtml = item.oldPrice ? `<del class="minicart-product__oldprice">${item.oldPrice}</del>` : '';
miniCart.append(`
<div class="minicart-product" data-product-id="${item.id}">
<a href="${item.url}" class="minicart-product__img">
<img src="${item.image}" alt="${item.name}">
</a>
<div class="minicart-product__main">
<a href="${item.url}" class="minicart-product__title">${item.name} <span style="color: #666;">(${item.quantity}${item.unit})</span></a>
<div class="minicart-product__row">
<p class="minicart-product__price">${item.price} ${oldPriceHtml}</p>
<button class="minicart-product__delete" data-id="${item.id}"><svg width="20" height="21" viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0_1149_35638)"><path d="M17.4993 3.83333H14.916C14.7226 2.89284 14.2109 2.04779 13.4671 1.4406C12.7233 0.833408 11.7929 0.501212 10.8327 0.5L9.16602 0.5C8.20584 0.501212 7.27545 0.833408 6.53164 1.4406C5.78783 2.04779 5.2761 2.89284 5.08268 3.83333H2.49935C2.27834 3.83333 2.06637 3.92113 1.91009 4.07741C1.75381 4.23369 1.66602 4.44565 1.66602 4.66667C1.66602 4.88768 1.75381 5.09964 1.91009 5.25592C2.06637 5.4122 2.27834 5.5 2.49935 5.5H3.33268V16.3333C3.33401 17.438 3.77342 18.497 4.55453 19.2782C5.33565 20.0593 6.39469 20.4987 7.49935 20.5H12.4993C13.604 20.4987 14.6631 20.0593 15.4442 19.2782C16.2253 18.497 16.6647 17.438 16.666 16.3333V5.5H17.4993C17.7204 5.5 17.9323 5.4122 18.0886 5.25592C18.2449 5.09964 18.3327 4.88768 18.3327 4.66667C18.3327 4.44565 18.2449 4.23369 18.0886 4.07741C17.9323 3.92113 17.7204 3.83333 17.4993 3.83333ZM9.16602 2.16667H10.8327C11.3496 2.1673 11.8536 2.32781 12.2757 2.6262C12.6978 2.92459 13.0172 3.34624 13.1902 3.83333H6.80852C6.9815 3.34624 7.30093 2.92459 7.723 2.6262C8.14508 2.32781 8.64912 2.1673 9.16602 2.16667ZM14.9993 16.3333C14.9993 16.9964 14.736 17.6323 14.2671 18.1011C13.7983 18.5699 13.1624 18.8333 12.4993 18.8333H7.49935C6.83631 18.8333 6.20042 18.5699 5.73158 18.1011C5.26274 17.6323 4.99935 16.9964 4.99935 16.3333В5.5H14.9993V16.3333Z" fill="#C4C4C4"/><path d="M8.33333 15.4997C8.55434 15.4997 8.76631 15.4119 8.92259 15.2556C9.07887 15.0993 9.16666 14.8873 9.16666 14.6663V9.66634C9.16666 9.44533 9.07887 9.23337 8.92259 9.07709C8.76631 8.92081 8.55434 8.83301 8.33333 8.83301C8.11232 8.83301 7.90036 8.92081 7.74408 9.07709C7.5878 9.23337 7.5 9.44533 7.5 9.66634V14.6663C7.5 14.8873 7.5878 15.0993 7.74408 15.2556C7.90036 15.4119 8.11232 15.4997 8.33333 15.4997Z" fill="#C4C4C4"/><path d="M11.6673 15.4997C11.8883 15.4997 12.1003 15.4119 12.2566 15.2556C12.4129 15.0993 12.5007 14.8873 12.5007 14.6663V9.66634C12.5007 9.44533 12.4129 9.23337 12.2566 9.07709C12.1003 8.92081 11.8883 8.83301 11.6673 8.83301C11.4463 8.83301 11.2343 8.92081 11.0781 9.07709C10.9218 9.23337 10.834 9.44533 10.834 9.66634V14.6663C10.834 14.8873 10.9218 15.0993 11.0781 15.2556C11.2343 15.4119 11.4463 15.4997 11.6673 15.4997Z" fill="#C4C4C4"/></g><defs><clipPath id="clip0_1149_35638"><rect width="20" height="20" fill="white" transform="translate(0 0.5)"/></clipPath></defs></svg></button>
</div>
</div>
</div>
`);
});
}
function updateTotalPrice(total, oldTotal) {
let cleanTotal = total;
if (oldTotal) {
$('.minicart-price').html(cleanTotal + ' <del class="minicart-price__old">' + oldTotal + '</del>');
} else {
$('.minicart-price').html(cleanTotal);
}
}
function updateCartCount(count) {
console.log('Updating cart count:', count);
var countElement = $('.header-cart__count');
var countElement2 = $('.header-cart__count2');
countElement.text(count).fadeOut(100, function() {
$(this).text(count).fadeIn(100);
});
countElement2.text(count).fadeOut(100, function() {
$(this).text(count).fadeIn(100);
});
console.log('Cart count updated in DOM:', countElement.text());
}
$(document).ready(function() {
updateCartButtons();
});
$(document).on('click', '.minicart-product__delete', function(e) {
e.preventDefault();
var button = $(this);
var productId = button.data('id');
$.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'remove_from_cart',
product_id: productId
},
success: function(response) {
updateCartButtons();
$(document.body).trigger('wc_fragment_refresh');
}
});
});
$(document).on('submit', 'form.product_page-kley', function(e) {
e.preventDefault();
var form = $(this);
var button = form.find('.product_page-submit');
var productId = button.data('id');
var quantity = parseInt(form.find('input[name="quantity"]').val()) || 1;
var select = form.find('.product_page-calc__select select');
var rawAttribute = select.data('attribute_name') || '';
var attribute_name = String(rawAttribute).replace('attribute_', '');
var selected_variation = select.val();
// Получаем цену из карточки товара (как она отображается)
var displayedPriceText = $('.product_page-price').text().replace(/\s/g, '').replace('₽', '');
var displayedTotal = parseFloat(displayedPriceText) || 0;
var pricePerUnit = displayedTotal / quantity;
$.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'add_variation_by_attribute',
product_id: productId,
quantity: quantity,
attribute_name: attribute_name,
attribute_value: selected_variation,
custom_price: pricePerUnit, // Передаём цену из карточки
},
beforeSend: function() {
button.addClass('loading');
},
success: function(response) {
button.removeClass('loading');
if (response.added) {
button.addClass('active');
}
$('.minicart__fon').css('display', 'flex');
$('.minicart').css('display', 'flex');
updateCartButtons();
$(document.body).trigger('wc_fragment_refresh');
},
error: function(xhr, status, error) {
console.error('Ошибка при отправке запроса:', error);
}
});
});
$(document).on('submit', 'form.product_page-trubi', function(e) {
e.preventDefault();
var form = $(this);
var button = form.find('.product_page-submit');
var productId = button.data('id');
var quantity = parseInt(form.find('input[name="quantity"]').val()) || 1;
var select = form.find('.product_page-calc__select select');
var rawAttribute = select.data('attribute_name') || '';
var attribute_name = String(rawAttribute).replace('attribute_', '');
var selected_variation = select.val();
// Получаем цену из карточки товара
var displayedPriceText = $('.product_page-price').text().replace(/\s/g, '').replace('₽', '');
var displayedTotal = parseFloat(displayedPriceText) || 0;
var pricePerUnit = displayedTotal / quantity;
$.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'add_variation_by_attribute',
product_id: productId,
quantity: quantity,
attribute_name: attribute_name,
attribute_value: selected_variation,
custom_price: pricePerUnit,
},
beforeSend: function() {
button.addClass('loading');
},
success: function(response) {
button.removeClass('loading');
if (response.added) {
button.addClass('active');
}
$('.minicart__fon').css('display', 'flex');
$('.minicart').css('display', 'flex');
updateCartButtons();
$(document.body).trigger('wc_fragment_refresh');
},
error: function(xhr, status, error) {
console.error('Ошибка при отправке запроса:', error);
}
});
});
$(document).on('submit', 'form.product_page-sterjni', function(e) {
e.preventDefault();
var form = $(this);
var button = form.find('.product_page-submit');
var productId = button.data('id');
var quantity = parseInt(form.find('input[name="quantity"]').val()) || 1;
var select = form.find('.product_page-calc__select select');
var rawAttribute = select.data('attribute_name') || '';
var attribute_name = String(rawAttribute).replace('attribute_', '');
var selected_variation = select.val();
// Получаем цену из карточки товара
var displayedPriceText = $('.product_page-price').text().replace(/\s/g, '').replace('₽', '');
var displayedTotal = parseFloat(displayedPriceText) || 0;
var pricePerUnit = displayedTotal / quantity;
$.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'add_variation_by_attribute',
product_id: productId,
quantity: quantity,
attribute_name: attribute_name,
attribute_value: selected_variation,
custom_price: pricePerUnit,
},
beforeSend: function() {
button.addClass('loading');
},
success: function(response) {
button.removeClass('loading');
if (response.added) {
button.addClass('active');
}
$('.minicart__fon').css('display', 'flex');
$('.minicart').css('display', 'flex');
updateCartButtons();
$(document.body).trigger('wc_fragment_refresh');
},
error: function(xhr, status, error) {
console.error('Ошибка при отправке запроса:', error);
}
});
});
jQuery(document).on('submit', 'form.product_page-simple', function(e) {
e.preventDefault();
var form = jQuery(this);
var button = form.find('.product_page-submit');
// Используем attr вместо data для надёжности, также проверяем value кнопки
var productId = button.attr('data-id') || button.val() || button.attr('value');
var quantity = parseInt(form.find('input[name="quantity"]').val()) || 1;
// Проверяем что productId определён
if (!productId) {
console.error('Ошибка: ID товара не найден');
console.log('Button:', button, 'data-id:', button.attr('data-id'), 'val:', button.val());
return;
}
console.log('Добавление в корзину: product_id=' + productId + ', quantity=' + quantity);
jQuery.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'woocommerce_ajax_add_to_cart',
product_id: productId,
quantity: quantity
},
beforeSend: function() {
button.addClass('loading');
},
success: function(response) {
button.removeClass('loading');
console.log('Ответ сервера:', response);
// Проверяем на ошибку в ответе
if (response && response.error) {
console.error('Ошибка при добавлении в корзину:', response.message || 'Неизвестная ошибка');
return;
}
// Успешное добавление - показываем миникорзину
button.addClass('active');
jQuery('.minicart__fon').css('display', 'flex');
jQuery('.minicart').css('display', 'flex');
if (response && response.fragments) {
jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash]);
}
// Обновляем корзину и триггерим refresh
jQuery(document.body).trigger('wc_fragment_refresh');
if (typeof updateCartButtons === 'function') {
updateCartButtons();
}
},
error: function(xhr, status, error) {
button.removeClass('loading');
console.error('Ошибка при добавлении в корзину:', error);
}
});
});
// Обработчик для формы калькулятора оргстекла
jQuery(document).on('submit', 'form.orgsteklo-calculator-form', function(e) {
e.preventDefault();
var form = jQuery(this);
var button = form.find('.single_add_to_cart_button');
var productId = button.attr('value') || form.data('product_id');
var quantity = parseInt(form.find('input[name="quantity"]').val()) || 1;
// Собираем данные калькулятора
var thickness = form.find('#orgsteklo_thickness').val();
var width = form.find('#orgsteklo_width').val();
var length = form.find('#orgsteklo_length').val();
jQuery.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'add_orgsteklo_to_cart',
product_id: productId,
quantity: quantity,
orgsteklo_thickness: thickness,
orgsteklo_width: width,
orgsteklo_length: length
},
beforeSend: function() {
button.addClass('loading');
},
success: function(response) {
button.removeClass('loading');
if (response.success) {
button.addClass('active');
jQuery('.minicart__fon').css('display', 'flex');
jQuery('.minicart').css('display', 'flex');
if (typeof updateCartButtons === 'function') {
updateCartButtons();
}
jQuery(document.body).trigger('wc_fragment_refresh');
} else {
alert(response.data ? response.data : 'Не удалось добавить товар в корзину');
}
},
error: function(xhr, status, error) {
button.removeClass('loading');
console.error('Ошибка при добавлении в корзину:', error);
alert('Произошла ошибка при добавлении товара в корзину');
}
});
});
// ГЛОБАЛЬНАЯ функция обновления количества (исправление)
window.updateQuantity = function(productId, quantity) {
var ajaxUrl = (window.wc_add_to_cart_params && wc_add_to_cart_params.ajax_url)
? wc_add_to_cart_params.ajax_url
: '/wp-admin/admin-ajax.php';
$.ajax({
url: ajaxUrl,
type: 'POST',
dataType: 'json',
data: {
action: 'update_cart_quantity',
product_id: productId,
quantity: quantity
},
success: function(response) {
if (response && response.fragments) {
$.each(response.fragments, function (key, value) {
$(key).replaceWith(value);
});
}
if (response && response.updated) {
if (typeof window.updateCartButtons === 'function') {
window.updateCartButtons();
}
$(document.body).trigger('wc_fragment_refresh');
} else {
console.error('Ошибка обновления количества');
}
},
error: function(xhr, status, error) {
console.error('Ошибка AJAX:', error);
}
});
};
$(document).on('click', '.cart-product__plus', function() {
const $container = $(this).closest('.cart-product-block');
const $input = $container.find('input[type="number"]');
const productId = $container.data('product-id');
let currentVal = parseInt($input.val());
let step = parseInt($input.attr('step')) || 1;
let max = parseInt($input.attr('max'));
if (!isNaN(currentVal)) {
let newVal = currentVal + step;
if (!isNaN(max)) {
newVal = Math.min(newVal, max);
}
$input.val(newVal).trigger('change');
window.updateQuantity(productId, newVal);
}
});
$(document).on('click', '.cart-product__minus', function() {
const $container = $(this).closest('.cart-product-block');
const $input = $container.find('input[type="number"]');
const productId = $container.data('product-id');
let currentVal = parseInt($input.val());
let step = parseInt($input.attr('step')) || 1;
let min = parseInt($input.attr('min')) || 1;
if (!isNaN(currentVal)) {
let newVal = currentVal - step;
newVal = Math.max(newVal, min);
$input.val(newVal).trigger('change');
window.updateQuantity(productId, newVal);
}
});
$(document).on('change', '.cart-product-block input[type="number"]', function() {
const $input = $(this);
const $container = $input.closest('.cart-product-block');
const productId = $container.data('product-id');
let val = parseInt($input.val());
if (isNaN(val) || val < 1) {
val = 1;
$input.val(val);
}
window.updateQuantity(productId, val);
});
});
function toNumber(val) {
if (val == null) return NaN;
return parseFloat(String(val).replace(',', '.'));
}
function getStepDecimals(step) {
const s = String(step);
const p = s.indexOf('.');
return p >= 0 ? (s.length - p - 1) : 0;
}
function clamp(val, min, max) {
if (!isNaN(min)) val = Math.max(val, min);
if (!isNaN(max)) val = Math.min(val, max);
return val;
}
function roundToStep(base, step, min) {
// округление к сетке шага от минимума (или 0)
const origin = isNaN(min) ? 0 : min;
const n = Math.round((base - origin) / step) * step + origin;
const dec = getStepDecimals(step);
return parseFloat(n.toFixed(dec));
}
$(document).on('click', '.cart-product__quantity-plus', function () {
// Игнорируем кнопки калькулятора оргстекла - у них свой обработчик
if ($(this).attr('id') === 'orgsteklo_qty_plus') {
return;
}
const $container = $(this).closest('.cart-product__quantity');
const $input = $container.find('input[type="number"]');
const productId = $container.data('product-id');
console.log("Test")
const curr = toNumber($input.val());
const step = toNumber($input.attr('step')) || 1;
const max = toNumber($input.attr('max'));
const min = toNumber($input.attr('min')) || 1;
if (!isNaN(curr)) {
let newVal = curr + step;
newVal = roundToStep(newVal, step, min);
newVal = clamp(newVal, min, max);
$input.val(newVal).trigger('change'); // для Woo
$(document).trigger('w:qty-changed', [{ productId, qty: newVal }]); // для своих скриптов
window.updateQuantity(productId, newVal); // глобальная
}
});
$(document).on('click', '.cart-product__quantity-minus', function () {
// Игнорируем кнопки калькулятора оргстекла - у них свой обработчик
if ($(this).attr('id') === 'orgsteklo_qty_minus') {
return;
}
const $container = $(this).closest('.cart-product__quantity');
const $input = $container.find('input[type="number"]');
const productId = $container.data('product-id');
const curr = toNumber($input.val());
const step = toNumber($input.attr('step')) || 1;
const max = toNumber($input.attr('max'));
const min = toNumber($input.attr('min')) || 1;
if (!isNaN(curr)) {
let newVal = curr - step;
newVal = roundToStep(newVal, step, min);
newVal = clamp(newVal, min, max);
$input.val(newVal).trigger('change');
$(document).trigger('w:qty-changed', [{ productId, qty: newVal }]);
window.updateQuantity(productId, newVal);
}
});
var products_swiper = new Swiper(".products-swiper", {
loop: true,
breakpoints: {
0: {
spaceBetween: 20,
slidesPerView: 1,
},
992: {
spaceBetween: 16,
slidesPerView: 4,
},
},
navigation: {
nextEl: ".products-next",
prevEl: ".products-prev",
},
});
var partners_swiper = new Swiper(".partners-swiper", {
loop: true,
breakpoints: {
0: {
spaceBetween: 16,
slidesPerView: 1.4,
},
992: {
spaceBetween: 16,
slidesPerView: 4.3,
},
},
navigation: {
nextEl: ".partners-next",
prevEl: ".partners-prev",
},
});
var history_swiper = new Swiper(".history-swiper", {
loop: true,
breakpoints: {
0: {
spaceBetween: 20,
slidesPerView: 1,
},
},
navigation: {
nextEl: ".history-next",
prevEl: ".history-prev",
},
});
var projects_swiper = new Swiper(".projects-swiper", {
loop: true,
breakpoints: {
0: {
spaceBetween: 20,
slidesPerView: 1,
},
},
navigation: {
nextEl: ".projects-next",
prevEl: ".projects-prev",
},
});
var product_page_thumbs = new Swiper(".product_page_thumbs", {
breakpoints: {
0: {
spaceBetween: 20,
slidesPerView: 1,
},
992: {
spaceBetween: 12,
slidesPerView: 6,
},
},
freeMode: true,
watchSlidesProgress: true,
});
var product_page_swiper = new Swiper(".product_page-swiper", {
spaceBetween: 10,
navigation: {
nextEl: ".product_page-next",
prevEl: ".product_page-prev",
},
pagination: {
el: '.product_page-pagination',
clickable: true,
},
thumbs: {
swiper: product_page_thumbs,
},
});
var banner_swiper = new Swiper(".banner-swiper", {
loop: true,
breakpoints: {
0: {
spaceBetween: 20,
slidesPerView: 1,
},
},
navigation: {
nextEl: ".banner-next",
prevEl: ".banner-prev",
},
});