PageSourceSearch

https://hircost.ru/local/components/hircost/sale.basket.basket/templates/.default/script.js

js hircost.ru collected 2026-10-07 00:30:10 UTC 14,244 bytes, 360 lines download raw bytes

1$(function() {
2    $(document).on('click', '[data-popup-opener="cart-remove"]', function() {
3        const $popup = $('[data-popup="cart-remove"]');
4        $popup.find('.cart-remove__text').text($(this).data('item-name'));
5        $popup.find('.js-cart-delete-item').attr('data-item-id', $(this).data('item-id'));
6		$popup.find('.js-cart-delete-item').attr('data-product-id', $(this).data('product-id'));
7        $popup.find('.js-cart-favorite-item').attr('data-item-id', $(this).data('item-id'));
8        $popup.find('.js-cart-favorite-item').attr('data-product-id', $(this).data('product-id'));
9		$popup.find('.js-cart-favorite-item').attr('data-product-price', $(this).data('product-price'));
10		$popup.find('.js-cart-favorite-item').attr('data-item-price', $(this).data('item-price'));
11		$popup.find('.js-cart-favorite-item').attr('data-item-name', $(this).data('item-name'));
12		$popup.find('.js-cart-favorite-item').attr('data-item-img', $(this).data('item-img'));
13        $popup.find('.cart-remove__img').attr('src', $(this).data('item-img'));
14        $popup.find('.cart-remove__img').attr('srcset', $(this).data('item-img') + ' ' + '152w');
15        if ($(this).data('is-certificate')) {
16            $popup.find('.js-cart-favorite-item').css('display', 'none');
17        } else {
18            $popup.find('.js-cart-favorite-item').css('display', 'inline-flex');
19        }
20
21        const $toast = $('#toast-remove-cart');
22        if($(this).data('item-img')) {
23        $toast.find('.toast__img-wrapper').html(`
24            <img class="toast__img full-size-img" src="${$(this).data('item-img')}" srcset="${$(this).data('item-img')} 100w" sizes="100vw" width="100" height="100" alt="">
25        `);
26        }
27        $toast.find('.toast__text').text($(this).data('item-name'));
28
29        history.replaceState(null, '', window.location.pathname);
30    });
31
32    $(document).on('click', '.js-cart-delete-item', function() {
33        const itemId = $(this).data('item-id');
34		const productId = $(this).data('product-id');
35
36        BX.ajax.runAction('hircost.Basket.remove', {
37            data: {
38                id: itemId
39            },
40        }).then(function (response) {
41			maxmaRemoveToCart(productId)
42            location.reload();
43        });
44    });
45
46    $(document).on('click', '.js-cart-favorite-item', function() {
47		const element = $(this);
48        const itemId = $(this).data('item-id');
49        const productId = $(this).data('product-id');
50
51		// Информация о товаре
52		const productInfo = {
53			productId: productId,
54			name: element.data('item-name'),
55			picture: element.data('item-img'),
56			price: element.data('item-price'),
57			pageUrl: window.location.href
58    	};
59
60
61        BX.ajax.runAction('hircost.Basket.remove', {
62            data: {
63                id: itemId
64            },
65        }).then(function (response) {
66			maxmaRemoveToCart(itemId);
67            location.reload();
68        });
69
70        BX.ajax.runComponentAction('hircost:favorites', 'addFavorite', {
71            mode: 'class',
72            data: {
73                productId
74            }
75        }).then(function(response) {
76            maxmaAddToFav(productInfo);
77        }).catch(function(error) {
78            //
79        });
80    });
81
82    function counterBasketHandler() {
83        return function(event) {
84            if (typeof this.timer !== 'undefined') {
85                clearTimeout(this.timer);
86            }
87            this.timer = setTimeout(() => {
88                const button = event.target;
89                const itemId = button.getAttribute('data-item-id');
90                const counterElement = button.parentElement.querySelector('[data-counter-value]');
91                const quantity = parseInt(counterElement.textContent);
92
93                const counterElementContainer = button.closest('.counter');
94                const maxValue = parseInt(counterElementContainer.getAttribute('data-counter-max'));
95
96                if (quantity > maxValue) {
97                    return;
98                }
99
100                BX.ajax.runAction('hircost.Basket.change', {
101                    data: {
102                        id: itemId,
103                        fields: {
104                            quantity
105                        }
106                    }
107                }).then(function(response) {
108                    location.reload();
109                }).catch(function(error) {
110                    console.error(error);
111                });
112            }, 500);
113        };
114    }
115
116    document.addEventListener('click', function(event) {
117        const target = event.target;
118        if (target.matches('[data-counter-plus], [data-counter-minus]')) {
119            counterBasketHandler()(event);
120        }
121    });
122
123    /*$(document).on('input', '.js-basket-promocode-input', function() {
124        if (typeof this.delayTimer !== 'undefined') {
125            clearTimeout(this.delayTimer);
126        }
127
128        this.delayTimer = setTimeout(() => {
129            const coupon = $(this).val();
130            const $errorField = $('.js-basket-promo-container').find('.js-basket-promo-error-text');
131
132            if (coupon.length > 0) {
133                BX.ajax.runAction('hircost.Basket.applyCoupon', {
134                    data: {
135                        coupon
136                    }
137                }).then(function (response) {
138                    location.reload();
139                }).catch(function (error) {
140                    $errorField.addClass('_active');
141                    $errorField.text(error.errors[0].message);
142                });
143            } else {
144                $errorField.text('');
145                $errorField.removeClass('_active');
146            }
147
148        }, 3000);
149    });
150
151    $(document).on('click', '.js-basket-promocode-clear', function() {
152        BX.ajax.runAction('hircost.Basket.clearCoupon', {
153            data: {}
154        }).then(function (response) {
155            location.reload();
156        });
157    });*/
158
159    $(document).on('change', '[data-basket-checkbox]', function() {
160        const itemId = $(this).data('item-id');
161        const action = !this.checked ? 'disableProduct' : 'enableProduct';
162
163        BX.ajax.runAction(`hircost.Basket.${action}`, {
164            data: {
165                itemId
166            }
167        }).then(function (response) {
168            location.reload();
169        });
170    });
171
172    $('.js-order-send-code').on('click', function() {
173        const $popup = $('[data-popup="sign-up-order"]');
174        const $form = $popup.find('.form-order-authorization');
175        const countryCode = $form.find('.iti__selected-dial-code').text().match(/\d+/);
176        const phone = countryCode + $form.find('[name="tel"]').val().replace(/[\s\-]/g, '');
177		
178        const button = $('.js-sign-in-send-code-again');
179        button.prop("disabled", true);
180        timerSend('.js-sign-in-send-code-again');
181
182        BX.ajax.runComponentAction('hircost:profile.authorization', 'sendCode', {
183            mode: 'class',
184            data: {
185                phone
186            }
187        }).then(function(response) {
188            if (response.data.error?.length > 0) {
189                printErrorInput('.js-order-phone-message', response.data.error);
190                return;
191            }
192
193            $('.js-sign-in-phone').text(phone);
194            $('.js-sign-in-phone-input').val(phone);
195            HircostApp.components.Popups.open('sign-in');
196            history.replaceState(null, '', window.location.pathname);
197        }).catch(function(error) {
198            printErrorInput('.js-order-phone-message', error);
199        });
200    });
201
202    $('.js-order-registration').on('click', function(event) {
203        event.preventDefault();
204        const $popup = $('[data-popup="sign-up-order"]');
205        const $form = $popup.find('.order-registration-form');
206        let formData = collectFormData($form);
207
208        const countryCode = $form.find('.iti__selected-dial-code').text().match(/\d+/);
209        formData.PERSONAL_PHONE = countryCode + formData.PERSONAL_PHONE.replace(/[\s\-]/g, '');
210		
211        const button = $('.js-sign-in-send-code-again');
212        button.prop("disabled", true);
213        timerSend('.js-sign-in-send-code-again');
214
215        BX.ajax.runComponentAction('hircost:profile.authorization', 'registration', {
216            mode: 'class',
217            data: {
218                formData,
219                isOrder: true
220            }
221        }).then(function(response) {
222            if (response.data.error?.length > 1) {
223                printErrorInput('.js-registration-message', response.data.error);
224            } else {
225
226				maxmaAddClientInfo(formData)
227
228                $('.js-sign-in-phone').text(formData.PERSONAL_PHONE);
229                $('.js-sign-in-phone-input').val(formData.PERSONAL_PHONE);
230                HircostApp.components.Popups.open('sign-in');
231                history.replaceState(null, '', window.location.pathname);
232            }
233        }).catch(function(error) {
234            printErrorInput('.js-registration-message', 'Произошла ошибка');
235        });
236    });
237});
238
239(() => {
240    function initBasketSizeSelects() {
241        // кастомный дропдаун шлёт change на самом select и без всплытия,
242        // поэтому обработчик вешаем на элемент, а не делегированно
243        document.querySelectorAll('.js--basket-item-change-size select').forEach((select) => {
244            if (select.dataset.sizeHandlerBound) {
245                return;
246            }
247
248            select.dataset.sizeHandlerBound = '1';
249            select.addEventListener('change', () => changeBasketItemOffer(select));
250
251            const initialOfferId = select.value;
252            const popup = select.closest('[data-cart-item]')?.querySelector('[data-cart-item-popup="size"]');
253            const submit = popup?.querySelector('.cart-item__popup-submit._size');
254            if (!submit || submit.dataset.sizeHandlerBound) {
255                return;
256            }
257
258            submit.dataset.sizeHandlerBound = '1';
259            submit.addEventListener('click', () => {
260                const checked = popup.querySelector('.size-radio__input:checked');
261                if (!checked || checked.disabled || checked.value === initialOfferId) {
262                    return;
263                }
264
265                select.value = checked.value;
266                select.dispatchEvent(new Event('change'));
267            });
268        });
269    }
270
271    function changeBasketItemOffer(select) {
272        setBasketBusy(true);
273
274        BX.ajax.runAction('hircost.Offer.changeOffer', {
275            mode: 'class',
276            data: {
277                basketItemId: select.getAttribute('data-basket-item-id'),
278                newOfferId: select.value
279            }
280        }).then(function(response) {
281            // при отказе перерисовка вернёт в селект реальный размер позиции
282            if (response.data.status !== 'success') {
283                console.error(response.data.message);
284            }
285
286            updateBasketPage();
287        }).catch(function(error) {
288            console.error(error);
289            updateBasketPage();
290        });
291    }
292
293    function setBasketBusy(isBusy) {
294        const cart = document.querySelector('[data-cart]');
295
296        if (cart) {
297            cart.style.pointerEvents = isBusy ? 'none' : '';
298        }
299    }
300
301    function updateBasketPage() {
302        const formData = new FormData();
303        formData.append('ajax', true);
304
305        fetch(window.location.pathname, {method: 'POST', body: formData})
306            .then(response => response.text())
307            .then(data => {
308                const div = document.createElement('div');
309                div.innerHTML = data;
310
311                const list = document.querySelector('.cart__list');
312                const newList = div.querySelector('.cart__list');
313
314                // корзина опустела или разметка не пришла — отдаём страницу серверу
315                if (!list || !newList) {
316                    window.location.reload();
317                    return;
318                }
319
320                list.innerHTML = newList.innerHTML;
321
322                // блок промокода лежит вне заменяемых узлов и переживает обновление
323                const info = document.querySelectorAll('.cart__info');
324                const newInfo = div.querySelectorAll('.cart__info');
325                if (info.length === newInfo.length) {
326                    info.forEach((el, i) => el.innerHTML = newInfo[i].innerHTML);
327                }
328
329                const submit = document.querySelector('.cart__submit-button');
330                const newSubmit = div.querySelector('.cart__submit-button');
331                if (submit && newSubmit) {
332                    submit.innerHTML = newSubmit.innerHTML;
333                    // у авторизованного покупателя кнопка это ссылка, свойство disabled ей не подходит
334                    if (newSubmit.hasAttribute('disabled')) {
335                        submit.setAttribute('disabled', 'disabled');
336                    } else {
337                        submit.removeAttribute('disabled');
338                    }
339                }
340
341                initBasketItems();
342                setBasketBusy(false);
343            })
344            .catch(error => {
345                console.error(error);
346                window.location.reload();
347            });
348    }
349
350    function initBasketItems() {
351        document.querySelectorAll('.cart__list [data-dropdown]').forEach((el) => new HircostApp.components.Dropdown(el));
352        document.querySelectorAll('.cart__list .counter').forEach((el) => new HircostApp.components.Counter(el));
353        document.querySelectorAll('.cart__list [data-cart-item]').forEach((el) => new HircostApp.components.CartItem(el));
354        // открывашки попапов удаления слушают клик напрямую, после подмены разметки их надо навесить заново
355        HircostApp.components.Popups.init();
356        initBasketSizeSelects();
357    }
358
359    initBasketSizeSelects();
360})()

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.