PageSourceSearch

https://servermall.by/g/s3/lp/lpc.v4/js/main.js

js servermall.by collected 2026-09-30 02:34:45 UTC 399,558 bytes, 11,667 lines download raw bytes

1;(function () {
2  var $win = $(window),
3    $doc = $(document),
4    $body = $("body"),
5    initializedMaps = [],
6    lpc_template = {},
7    isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
8	isApple = /iPod|iPad|iPhone/i.test(navigator.userAgent);
9
10	window.lpc_template = lpc_template;
11
12	lpc_template.queue = {};
13	
14	$body.on('click', 'a[href^="popup:"]', function (e) {
15        e.preventDefault();
16    });
17
18    function lpcCreateBlockProducts(
19		jquery_block,
20		dataOptionOption,
21		callBack = { beforeAjax: null, complete: null }
22    ){
23        class createBLockProduct {
24                    
25            constructor($block) {
26                this.$block = $block;
27				this.response = null;
28				this.dataSliderInit = null,
29				this.spoilerInit = null,
30				this.extenSettingBegin = function() {
31					let _this = this;
32					_this.dataSliderInit = _this.$block.attr('data-ajax-slider-init') ? _this.$block : _this.$block.find('.splide-init');
33					if (_this.dataSliderInit.length && _this.dataSliderInit.find('.splide .is-active').length) {
34						_this.dataSliderInit.each(function() {
35							$(this).removeAttr('data-ajax-slider-init');
36							let slider = $(this).find(".splide")[0];
37							let splide = new Splide(slider);
38							splide.mount();
39							splide.destroy();
40						})
41					}
42				
43					_this.spoilerInit = _this.$block.hasClass('spoiler-init') ? _this.$block : _this.$block.find('.spoiler-init');
44					if (_this.spoilerInit.length) {
45						_this.spoilerInit.each(function() {
46							$(this).removeClass('spoiler-init');
47						})
48					}
49				};
50				this.extenSettingFinish = function(){
51					let _this = this;
52					if (_this.dataSliderInit.length) {
53						_this.dataSliderInit.each(function() {
54							$(this).attr('data-ajax-slider-init', 'true');
55							$(this).find('.splide.is-active').removeClass('.is-active');
56						})
57					}
58					if (_this.spoilerInit.length) {
59						_this.spoilerInit.each(function() {
60							$(this).addClass('spoiler-init');
61						})
62					}
63					setTimeout(() => {
64						lpc_template.queue.spoilerBlock(_this.$block);
65						_this.setAjaxSlider(_this.$block);
66						setTimeout(() => {
67							lpc_template.queue.lg(_this.$block);
68						}, 300);
69					}, 300);
70		
71				};
72				this.setAjaxSlider = function() {
73					
74					let _this = this;
75					let $block = _this.$block.attr('data-ajax-slider-init') ? _this.$block : _this.$block.find('[data-ajax-slider-init]');
76					if ($block.length) {
77			
78						if ($block.data('slider-thumb-init') != true) {
79							$block.each(function() {
80								let $this = $(this);
81								let $alignItem = $this.find($this.data('align-item'));
82								let mediaGap = $this.data('margin');
83								let mediaPerPage = $(this).data('count');
84								if ($(this).data('move')) {
85									var $mediaMove = $(this).data('move');
86			
87								} else {
88									var $mediaMove = 1;
89								}
90								
91								if ($this.find('.splide').not('.is-active').length != 0) {
92									let splide = new Splide($this.find('.splide').not('.is-active')[0], {
93										autoplay: $this.data('autoplay'),
94										speed: $this.data('speed'),
95										interval: $this.data('pause'),
96										/*rewind: $this.data('infinite'),*/
97										lazyLoad: $this.data('lazy-load'),
98										rewind: true,
99										perMove: $mediaMove,
100										perPage: checkInitPerPage()
101									});
102			
103			
104									splide.mount();
105			
106									sliderBreakPoints();
107			
108									document.addEventListener('lpcPopupOpened', function() {
109										splide.refresh();
110									});
111			
112									document.addEventListener('dataMediaSourceChange', sliderBreakPoints);
113			
114									function sliderBreakPoints() {
115										let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
116			
117										setTimeout(function() {
118											if ($alignItem.length) {
119												let itemHeight = $alignItem.outerHeight() / 2;
120												let arrowsPosition = itemHeight + $alignItem.position().top;
121			
122												$this.find('.splide__arrow').css('top', arrowsPosition);
123											}
124										}, 100);
125			
126										switch (dataMediaSource) {
127											case 'media-xl':
128												splide.options = {
129													arrows: true,
130													pagination: true,
131													gap: mediaGap[0],
132													perPage: mediaPerPage[0],
133												};
134			
135												break;
136											case 'media-lg':
137												splide.options = {
138													arrows: true,
139													pagination: true,
140													gap: mediaGap[1],
141													perPage: mediaPerPage[1],
142												};
143			
144												break;
145											case 'media-md':
146												splide.options = {
147													arrows: true,
148													pagination: true,
149													gap: mediaGap[2],
150													perPage: mediaPerPage[2],
151												};
152			
153												break;
154											case 'media-sm':
155												splide.options = {
156													arrows: false,
157													pagination: true,
158													rewindByDrag: true,
159													gap: mediaGap[3],
160													perPage: mediaPerPage[3],
161												};
162			
163												break;
164											case 'media-xs':
165												splide.options = {
166													arrows: false,
167													pagination: true,
168													rewindByDrag: true,
169													gap: mediaGap[4],
170													perPage: mediaPerPage[4],
171												};
172			
173												break;
174										}
175									};
176			
177									function checkInitPerPage() {
178										let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
179			
180										switch (dataMediaSource) {
181											case 'media-xl':
182												return mediaPerPage[0]
183												break;
184											case 'media-lg':
185												return mediaPerPage[1]
186												break;
187											case 'media-md':
188												return mediaPerPage[2]
189												break;
190											case 'media-sm':
191												return mediaPerPage[3]
192												break;
193											case 'media-xs':
194												return mediaPerPage[4]
195												break;
196										};
197									};
198			
199									//sliderObjectItems[splide.root.id] = splide;
200								}
201							});
202						}
203					}
204				};
205				this.getCompare = function() {
206					var popup_data;
207					
208					if (shop2.my.gr_new_notification) {
209						var compare_arrow = '<i class="gr-mask-icon"><svg class="gr-svg-icon"><use xlink:href="#icon_shop_notify_arr"></use></svg></i>';
210					} else {
211						var compare_arrow = '<i><svg class="gr-svg-icon"><use xlink:href="#icon_shop_notify_arr"></use></svg></i>';
212					}
213					
214					if (shop2.my.gr_popup_compare) {
215						popup_data = ' data-remodal-target="compare-preview-popup"';
216					};
217					
218					let $document = $(document);
219					
220					if (shop2.my.gr_new_notification) {
221						var compareBtn = '<a href="' + shop2.uri + '/compare" class="go-to-compare-btn gr-compare-tooltip-btn"'+popup_data+' target="_blank">'+ _s3Lang.SHOP2_ADD_TO_COMPARE3 +' '+compare_arrow+'</a>';
222					  	var compareBtn2 = '<a href="' + shop2.uri + '/compare" class="go-to-compare-btn gr-compare-tooltip-btn"'+popup_data+' target="_blank">'+ _s3Lang.SHOP2_GO_TO_COMPARE +' '+compare_arrow+'</a>';
223				
224					} else {
225						var compareBtn = '<a href="' + shop2.uri + '/compare" class="go-to-compare-btn"'+popup_data+' target="_blank">'+ _s3Lang.SHOP2_ADD_TO_COMPARE3 +' '+compare_arrow+'</a>';
226					  	var compareBtn2 = '<a href="' + shop2.uri + '/compare" class="go-to-compare-btn"'+popup_data+' target="_blank">'+ _s3Lang.SHOP2_GO_TO_COMPARE +' '+compare_arrow+'</a>';
227				
228					}
229					
230					function update(el, res) {
231						
232						if (shop2.my.gr_new_notification) {
233							var $form = $(el).closest('form');
234							var $image = $form.find('.gr-product-image--js');
235							var isAdded = $(el).closest('.lpc-product-compare ').hasClass('product-compare--added');
236						}
237						
238						$('input[type=checkbox][value=' + el.val() + ']').closest('.lpc-product-compare').replaceWith(res.data);
239						$('input[type=checkbox][value=' + el.val() + ']').closest('.product-compare').addClass('lpc-product-compare lp-header-text-3').removeClass('product-compare');
240						$('input[type=checkbox][value=' + el.val() + ']').closest('.gr-compare-checkbox').addClass('lpc-product-compare__checkbox').prepend('<i class="lpc-product-compare__icon"></i>');
241						$('input[type=checkbox][value=' + el.val() + ']').closest('.gr-compare-plus').addClass('lpc-compare-plus').prepend('<i class="lpc-product-compare__icon"></i>');
242						
243						
244						//$('.lpc-product-compare-added a span').html(res.count);
245						//$('.gr-compare-btn .gr-compare-btn-amount').html(res.count);
246						$('.gr-compare-btn .gr-compare-btn-amount').html(res.count);	
247						
248						if (+$('.gr-compare-btn .gr-compare-btn-amount').text() == '0') {
249							$('.gr-compare-btn').removeClass('active');
250						} else {
251							$('.gr-compare-btn').addClass('active');
252						};
253						
254						if (!$('.compare-remodal').hasClass('remodal-is-opened')) {
255							if (shop2.my.gr_new_notification) {
256								if (!isAdded) {
257									shop2.popupNotification({
258									    "itemContent": '<span class="gr-compare-tooltip-counter">
258'+res.count+'</span>' + ' '+ _s3Lang.SHOP2_PRODUCT_ADDED +' ' + compareBtn, 
259									    "itemClass": "gr-notification__item--compare",
260									    "itemImage": shop2.my.gr_hide_msg_image ? false : true,
261									    "itemSrc": $image.find('img').attr('src'),
262									    "itemHref": $image.attr('href'),
263									    "itemContain": $image.data('image-view'),
264									    "itemSize": $image.data('image-size'),
265									});
266								};
267							} else {
268								shop2.msg('<span class="go-to-compare-count">'+res.count+'</span>' + ' '+ _s3Lang.SHOP2_PRODUCT_ADDED +' ' + compareBtn, $('body'));
269							}
270						};
271				
272						if (res.panel) {
273							$('#shop2-panel').replaceWith(res.panel);
274						};
275					}
276				
277					$document.on('click', '.lpc-product-compare input:checkbox', function(d) {
278						
279						let $this = $(this),
280							action = $this.attr('checked') ? 'del' : 'add';
281							
282							if (shop2.my.gr_new_notification) {
283								var $form = $($this).closest('form');
284								var $image = $form.find('.gr-product-image--js');
285							}
286							
287						lpc_template.queue.lpcCompare.action(action, $this.val(), function(res, status) {
288							if (status == 'success') {
289								if (res.errstr) {
290									if (!$('.compare-remodal').hasClass('remodal-is-opened')) {
291										if (shop2.my.gr_new_notification) {
292						
293											shop2.popupNotification({
294											    "itemContent": res.errstr + '<div class="go-to-compare-error">'+compareBtn2+'</div>', 
295											    "itemClass": "gr-notification__item--compare",
296											    "itemImage": shop2.my.gr_hide_msg_image ? false : true,
297											    "itemSrc": $image.find('img').attr('src'),
298											    "itemHref": $image.attr('href'),
299											    "itemContain": $image.data('image-view'),
300											    "itemSize": $image.data('image-size'),
301											});
302										} else {
303											shop2.msg(res.errstr + '<div class="go-to-compare-error">'+compareBtn2+'</div>', $('body'));
304										}
305									}
306									$this.prop('checked', false);
307								} else {
308									update($this, res);
309									
310									if (action == 'del' && !$('.compare-remodal').hasClass('remodal-is-opened')) {
311										if (shop2.my.gr_new_notification) {
312						
313											shop2.popupNotification({
314											    "itemContent": _s3Lang.SHOP2_PRODUCT_REMOVED_COMPARE, 
315											    "itemClass": "gr-notification__item--compare",
316											    "itemImage": shop2.my.gr_hide_msg_image ? false : true,
317											    "itemSrc": $image.find('img').attr('src'),
318											    "itemHref": $image.attr('href'),
319											    "itemContain": $image.data('image-view'),
320											    "itemSize": $image.data('image-size'),
321											});
322										} else {
323											shop2.msg(_s3Lang.SHOP2_PRODUCT_REMOVED_COMPARE, $('body'));
324										}
325									}
326									if (d.panel) {
327										$('#shop2-panel').replaceWith(d.panel);
328									}
329								}
330							}
331							//$('.gr-compare-btn .gr-compare-btn-amount').html(res.count);
332						});
333					});
334				}
335				
336				this.receivingDataPopup = function() {
337					var _this = this;
338					let $blockList = _this.$block.find('.lpc-query-products');
339					let optionLpcDecorPopup = {};
340					
341					optionLpcDecorPopup['lpc_product_show_options'] = $blockList.attr('data-lpc-product-sh
341ow-options');
342					optionLpcDecorPopup['lpc_product_on_lg'] = $blockList.attr('data-lpc-product-on-lg');
343					optionLpcDecorPopup['lpc_product_vendor'] = $blockList.attr('data-lpc-product-vendor');
344					optionLpcDecorPopup['lpc_product_rating'] = $blockList.attr('data-lpc-product-rating');
345					optionLpcDecorPopup['lpc_product_article'] = $blockList.attr('data-lpc-product-article');
346					optionLpcDecorPopup['lpc_product_annonce'] = $blockList.attr('data-lpc-product-annonce');
347					optionLpcDecorPopup['lpc_product_sale'] = $blockList.attr('data-lpc-product-sale');
348					optionLpcDecorPopup['lpc_product_amount_flag'] = $blockList.attr('data-lpc-product-amount-flag');
349					optionLpcDecorPopup['lpc_product_amount'] = $blockList.attr('data-lpc-product-amount');
350					optionLpcDecorPopup['lpc_product_one_click'] = $blockList.attr('data-lpc-product-one-click');
351					optionLpcDecorPopup['lpc_product_img'] = $blockList.attr('data-lpc-product-img');
352
353					
354					$(document).on('click', '.lpc-shop-lot__quick-trigger', function(e) {
355						if(_this.$block.attr('id') == $(this).closest('.lpc-shop-lot').attr('id')){
356							var $parentBlock = $(this).closest('.lpc-shop-lot'),
357								$popupBody = $parentBlock.find(".lpc-shop-lot__popup-body"),
358								$popupFixPanel = $parentBlock.find(".lpc-shop-lot__popup-fix-panel");
359								
360							e.preventDefault();
361	
362							let $this = this;
363							var url = $(this).attr("data-url") || $this.attr("href");
364								url += '?&products_only=1';
365								url += '?&lpc_product_card_popup=1';
366							
367							$.ajax({
368								url: url,
369								data: {
370									'option_decor_popup': JSON.stringify(optionLpcDecorPopup),
371								},
372								success: function(response) {
373									// 1935. 07.04.2025. Обрезаю все теги скриптов в ответе аякс запроса. Сделано это чтобы исключить дублирование ЖП.
374									//$popupBody.html(response);
375									const cleanedHtml = response.replace(/(<script[^>]*>[\s\S]*?shop2\.quickRefs[\s\S]*?<\/script>)|<script[^>]*>[\s\S]*?<\/script>/gi, '$1');
376									$popupBody.html(cleanedHtml);
377								},
378								// success
379							
380								complete: function() {
381									var $blockWidth = $('.lpc-shop-lot:not(._not-data)').width();
382									var $priceClone = $parentBlock.find(".lpc-product-additional__top").find(".lpc-lot-popup__price-inner")
383									var $buyBtnClone = $parentBlock.find(".lpc-product-additional__top").find(".lpc-lot-popup-btns");
384									 
385									$("html").addClass('lpc-shop-popup-scroll');
386									
387									setTimeout(function() {
388										$('.lpc-lot-popup').css('max-width',$blockWidth);
389									}, 1);
390									
391									
392									$(window).on("resize", function () {
393										var $blockWidth = $('.lpc-shop-lot').width();
394										$('.lpc-lot-popup').css('max-width',$blockWidth);
395									}).trigger("resize");
396		
397								
398									setTimeout(function() {
399										lpc_template.queue.sliderBlockThumbGallery($('body'));
400									}, 200); 
401									
402									$parentBlock.find('.lpc-favorite-btn').on('click', function(){
403										$(this).find("a").addClass("lp-header-text-3");
404									});
405									
406									setTimeout(function() {
407										if ($popupFixPanel.find('.lpc-lot-popup__price-inner').length == 0) {
408											$priceClone.clone().appendTo($popupFixPanel);
409											$buyBtnClone.clone().appendTo($popupFixPanel);
410										}
411									}, 200);
412									
413									var $sliderItemsLength = $parentBlock.find('.lpc-lot-popup-slider__thumb').length,
414										$sliderArrowHideCountXl = $parentBlock.find('.lpc-lot-popup-slider__thumbs').data('count-hide-xl'),
415										$sliderArrowHideCountLg = $parentBlock.find('.lpc-lot-popup-slider__thumbs').data('count-hide-lg');
416										
417									if($sliderItemsLength < $sliderArrowHideCountXl) {
418										$parentBlock.find('.lpc-lot-popup-slider__thumbs-body').addClass('xl-not-arrow');
419									}
420									if($sliderItemsLength < $sliderArrowHideCountLg) {
421										$parentBlock.find('.lpc-lot-popup-slider__thumbs-body').addClass('lg-not-arrow');
422									}
423									
424									setTimeout(function() {
425										lpc_template.queue.lgNew($('body'));
426									}, 100);
427									
428									/*$('.lpc-shop-lot__popup .lpc-options-more').each(function(){
429										$(this).on('click', function(){
430											$(this).toggleClass('active');
431											$(this).siblings('.lpc-options-container').slideToggle();
432										});
433									});*/
434									
435									lpc_template.queue.fixingPanelShow($('body'));
436								}//complete
437							});
438							setTimeout(function() {
439								$parentBlock.find(".lpc-shop-lot__popup").addClass('active');
440							}, 50);
441						}
442					});
443					$('.lpc-shop-lot__popup-back, .lpc-shop-lot__popup-close').on('click', function(){
444						$(".lpc-shop-lot__popup").removeClass('active');
445						
446						$(this).closest('.lpc-shop-lot__popup').find(".lpc-lot-popup").html("");
447						$('.lpc-shop-lot__popup-fix-panel').find('div').remove();
448						$("html").removeClass('lpc-shop-popup-scroll');
449					});
450				};
451            }
452            
453			getProducts() {
454				let _this = this;
455				/*let folderId = _this.$block.find('.block-id-folder').text();*/
456				
457				let folderId = _this.$block.find('.block-id-folder');
458				if(folderId.length){
459					folderId = _this.$block.find('.block-id-folder').text();
460				}else {
461					folderId = _this.$block.data('folder-attr');
462				}
463				
464				// Формируем URL для GET-запроса
465				dataOptionOption.param.search.folder_id = folderId;
466				var url = '/-/x-api/v1/public/?method=shop2/getProductsBySearch';
467				
468				if( typeof callBack.beforeAjax == 'function'){
469					callBack.beforeAjax(_this);
470				}
471			
472				if (folderId == 'not_found') {
473					return;
474				}else{
475					$.ajax({
476						url: url,
477						dataType: "JSON",
478						data: dataOptionOption,
479				
480						success: function(response) {
481							if (response.result.success) {
482								_this.response = response;
483								_this.$block.find('.lpc_product_not_found_vv').removeClass('show');
484				
485								var dataHTML = response.result.html;
486								
487								
488								let containerProductForTemplate = _this.$block.find(`.containerProductForTemplate`);
489							 
490								if (!response.result.html) {
491									containerProductForTemplate.closest('.lpc-block').addClass("_not-data");
492									
493									return false;
494								};
495								
496								containerProductForTemplate.removeAttr('style');
497								containerProductForTemplate.html(dataHTML);
498								
499							}
500						}, // success
501				
502						complete: function() {
503							if( typeof callBack.complete == 'function'){
504								callBack.complete(_this);
505							}
506						} //complete
507					});
508				}
509			}
510            changeFolder(folderId) {
511                let _this = this;
512                /*
513                _this.$block.find('.block-id-folder').text(folderId).addClass('modified modified-text');
514        		*/
515                let blockFolderId = _this.$block.find('.block-id-folder');
516                
517                if(blockFolderId.length){
518                	blockFolderId.text(folderId);
519                }else {
520					_this.$block.attr('data-folder-attr', folderId);
521				}
522        		
523        		
524                _this.getProducts();
525            }
526            
527            createSelect() {
528                var _this = this;
529                /*parent wraper */
530                let containerFolder = _this.$block.find(`.lpc-select-folder-container`); // mainContainer
531        
532        
533                let queryFolder = containerFolder.find(`.lpc-query-folder`); // Logic query
534                let selectFolder = queryFolder.find('.lpc-query-folder__select');
535                /*parent wraper */
536        
537                let folderInputSelected = queryFolder.find('.lpc-query-folder__input'); /* preview BTN */
538        
539                let folderId = queryFolder.attr('data-folder_id');
540        
541                let selectFolderBody = queryFolder.find('.lpc-query-folder__body'); /* option BOdy */
542        
543                let flagLoadFolder = 0;
544        
545                async function fetchAndCreateSelect() {
546                    try {
547                        // Создаем параметры запроса
548                        let params = new URLSearchParams();
549                        params.append('param[type]', 'shop2');
550                        params.append('param[depth]', '99');
551        
552                        // Формируем URL для GET-запроса
553                        let url = '/-/x-api/v1/public/?method=folder/getTree&' + params.toString();
554        
555                        // Отправляем GET-запрос с использованием fetch
556                        let response = await fetch(url, {
557                            method: 'GET',
558                            headers: {
559                                'Content-Type': 'application/json'
560                            }
561                        });
562                        
563                        if (!response.ok) {
564                            throw new Error('Ошибка при выполнении запроса');
565                        }
566        
567                        let data = await response.json();
568                        
569                        if (data.result.success) {
570                            let items = data.result.items;
571                            
572                            // Нет категории магазина
573                            if (!items.length) {
574                                queryFolder.addClass('lpc-shop-not-found');
575                                return false;
576                            }
577        
578                            items.shift(); // удаляет первую категорию
579                            // Создаем варианты (option) выпадающего списка и добавляем их к существующему select
580        
581                            function createSelector(data) {
582                                var rootUL = document.createElement('ul');
583                                var levelObject = {};
584                                var parentLi = null;
585        
586                                data.forEach(item => {
587                                    var li = document.createElement('li');
588                                    var div = document.createElement('div');
589                                    div.className = 'lpc-query-folder__option lpc-query__option';
590                                    div.setAttribute('data-folder_id', item.folder_id);
591        
592                                    var span = document.createElement('span');
593        
594                                    function decodeHtmlEntities(input) {
595                                        var doc = new DOMParser().parseFromString(input, "text/html");
596                                        return doc.documentElement.textContent;
597                                    }
598                                    span.textContent = decodeHtmlEntities(item.folder_name);
599                                    div.title = decodeHtmlEntities(item.folder_name);
600        
601                                    var i = document.createElement('i');
602                                    i.textContent = `(${item.items})`;
603        
604                                    div.appendChild(span);
605                                    div.appendChild(i);
606                                    li.appendChild(div);
607        
608                                    let level = Number(item._level);
609        
610                                    if (level == 1) {
611                                        rootUL.appendChild(li);
612                                        parentLi = li;
613                                        levelObject = {};
614                                    } else {
615                                        if (!levelObject[level]) {
616                                            levelObject[level] = document.createElement('ul');
617                                            parentLi.appendChild(levelObject[level]);
618                                        }
619                                        levelObject[level].appendChild(li);
620                                        parentLi = li;
621                                    }
622        
623                                    if (folderId && folderId == item.folder_id) {
624                                        folderInputSelected.find('span').text(
625                                            $(div)
626                                            .addClass('selected active')
627                                            .find('span')
628                                            .text()
629                                        );
630                                        //$( div ).addClass('active');
631                                    }
632                                });
633        
634                                return rootUL;
635                            }
636                            selectFolderBody.append(createSelector(items));
637        
638                            var itemOption = selectFolderBody.find('.lpc-query__option');
639        
640                            selectFolderBody.find('.search-folder-input').on('input', function() {
641                                var value = $(this).val();
642                                var searchText = value.toLowerCase();
643        
644                                for (var i = 0; i < itemOption.length; i++) {
645                                    var $this = $(itemOption[i]);
646        
647                                    if (value) {
648                                        $this.removeClass('unfiltered');
649                                    }
650        
651                                    var title = $this.attr('title').toLowerCase();
652        
653                                    if (title.includes(searchText)) {
654                                        $this.removeClass('unfiltered');
655                                    } else {
656                                        $this.addClass('unfiltered');
657                                    }
658                                }
659                            })
660        
661                            return true;
662                        }
663                    } catch (error) {
664                        console.error('Ошибка при выполнении запроса:', error);
665                        return false;
666                    }
667                }
668        
669                async function loadSelectedOption() {
670                    let awaitCreateSelect = await fetchAndCreateSelect(); // Ждем выполнения
671        
672                    if (awaitCreateSelect) {
673                        queryFolder
674                            .removeClass('load')
675                            .addClass('loaded');
676        
677                        folderInputSelected.on('click', function(e) {
678                            selectFolder.toggleClass("open");
679                        });
680                        let queryFolderOption = queryFolder.find('.lpc-query-folder__option'); /* option select */
681        
682                        queryFolderOption.on('click', function(e) {
683                            let $this = $(this);
684                            let folderId = $this.data('folder_id');
685                            queryFolderOption.removeClass('active');
686                            $this
687                                .addClass('active')
688                                .siblings()
689                                .removeClass('active');
690                            folderInputSelected.find('span').text($this.find('span').text());
691                            selectFolder.toggleClass("open");
692        
693                            _this.changeFolder(folderId);
694        
695                            if (!flagLoadFolder) {
696                                queryFolder.addClass('folder-selected')
697                            }
698        
699                        });
700                    }
701                }
702                loadSelectedOption();
703            }
704        };
705        if( typeof jquery_block != 'undefined' ){
706            var getProductDataLpcCLass = new createBLockProduct(jquery_block);
707                  
708            if (s3LP.is_cms) {
709                getProductDataLpcCLass.createSelect();
710            }
711            
712            getProductDataLpcCLass.getProducts();
713
714			return getProductDataLpcCLass;
715        }
716    };
717    
718	
719	lpc_template.queue.lpcWrapText = function ($self) {
720	    var $blocks = $self.hasClass('js-wrap-text') ? $self : $self.find('.js-wrap-text');
721	    
722	    if (!$blocks.length) return;
723	
724	    $blocks.each(function () {
725	        var $block = $(this);
726	        var bigTextEl = $block.find('.lpc-text-10-big-text-body')[0];
727	        var wrapEl = $block[0];
728	
729	        // 1. Функция синхронизации fontSize для конкретного блока
730	        function syncFontSize() {
731	            if (bigTextEl && wrapEl) {
732	                const style = window.getComputedStyle(bigTextEl);
733	                wrapEl.style.fontSize = style.fontSize;
734	            }
735	        }
736	
737	        syncFontSize();
738	
739	        // Наблюдатель за изменениями стиля конкретного заголовка
740	        if (bigTextEl) {
741	            const observer = new MutationObserver(syncFontSize);
742	            observer.observe(bigTextEl, {
743	                attributes: true,
744	                attributeFilter: ['style', 'class']
745	            });
746	        }
747	
748	        // 2. Логика обтекания (только если есть внутренний блок)
749	        var $inner = $block.find('.lpc-text-10-inner._bottom-vertical');
750	        
751	        if ($inner.length) {
752	            $(window).on("resize.lpcWrap", function () {
753	                setTimeout(function () {
754	                    var mediaTypeCheck = $('.decor-wrap').attr('data-media-source');
755	                    
756	                    if (mediaTypeCheck === "media-xs" || mediaTypeCheck === "media-sm") {
757	                        $inner.removeAttr('style');
758	                    } else {
759	                        const $bigText = $block.find('.lpc-text-10-big-text-body');
760	                        const $smallText = $block.find('.lpc-text-10-small-text-body');
761	                        
762	                        // Получаем line-height
763	                        let lineHeight = parseFloat($bigText.css('line-height'));
764	                        if (isNaN(lineHeight) || lineHeight < 10) {
765	                            lineHeight = parseFloat($bigText.css('font-size'));
766	                        }
767	
768	                        const totalHeight = $bigText.height();
769	                        const totalSmallHeight = $smallText.height();
770	                        
771	                        // Расчеты
772	                        const offset = lineHeight;
773	                        const propValue = Math.ceil(totalSmallHeight / lineHeight) * offset;
774	                        const smallGap = totalHeight - propValue + 1;
775	
776	                        $inner.css({
777	                            'padding-top': smallGap + 'px',
778	                            'shape-outside': `inset(${smallGap}px 0 0 0)`,
779	                            'height': propValue + 'px'
780	                        });
781	                        
782	                        /* Консоль для отладки конкретного блока */
783	                        // console.log('Block processed:', wrapEl);
784	                    }
785	                }, 200);
786	            }).trigger("resize.lpcWrap");
787	        }
788	    });
789	};
790    
791    lpc_template.queue.updatedContacts = function ($self) {
792	    let $blocks = $self.find('.lpc_updated_init');
793	    
794	    if ($blocks.length) {
795	        $blocks.each(function () {
796	            let $block = $(this);
797	            let $phones = $block.find('.lpc_phone');
798	            
799	            $phones.each(function () {
800	                let $phone = $(this);
801	                let $nextButtons = $phone.nextUntil('.lpc_phone, :not(.lpc_button.hidden_text)').filter('.lpc_button.hidden_text');
802	               
803	                if ($nextButtons.length) {
804	                	let $wrapper = $('<div class="lpc-updated-contacts__item-wrap"></div>');
805	                	
806	                    $nextButtons.each(function () {
807	                        $(this).css({marginTop: '0'}); 
808	                         $wrapper.append($(this));
809	                    });
810	                    
811	                    $phone.append($wrapper);
812	                }
813	                
814	                let $itemBox = $phone.find('.lpc-updated-contacts__item-box');
815	              
816	                if ($itemBox.length) {
817	                    $itemBox.css('margin-right', '10px');
818	                }
819	            });
820	        });
821	    }
822	};
823	
824	
825	lpc_template.queue.refreshForm = function ($self) {
826	    
827	    const $refreshButton = $('.lpc-refresh-form');
828	    if (!$refreshButton.length) return;
829	
830	    $refreshButton.each(function () {
831	        const $button = $(this);
832	
833	        const href = $button.attr('href');
834	        if (!href) return;
835	        
836	        const popupMatch = href.match(/popup:_lp_block_(\d+)/);
837	        if (!popupMatch) return;
838	
839	        const popupId = popupMatch[1];
840	        const $popupElement = $(`[data-block-id="${popupId}"]`);
841	        if (!$popupElement.length) return;
842	
843	        const $form = $popupElement.find('.lp-form-tpl');
844	        if (!$form.length) {
845	            console.warn('Форма не найдена внутри попапа');
846	            return;
847	        }
848	
849	        const apiUrl = $form.attr('data-lpc-api-url');
850	        if (!apiUrl) {
851	            console.warn('API URL не найден у формы');
852	            return;
853	        }
854	
855	        const $successBlock = $popupElement.find('.hide-on-success');
856	        let $successClone = null;
857	        if ($successBlock.length) {
858	            $successClone = $successBlock.clone(true);
859	        }
860	
861	        $button.off('click.refreshForm').on('click.refreshForm', function (e) {
862	            e.preventDefault();
863	
864	            const isFormSubmitted = $popupElement.find('.lp-form-tpl__success').length > 0;
865	            
866	            if (!isFormSubmitted) return;
867	
868	            const $formOld = $popupElement.find('.lp-form-tpl');
869	            const $productBlock = $button.closest('.lpc-product-name');
870        		const prodName = $productBlock.find('[data-name-product]').data('name-product') || '';
871	
872	            $.ajax({
873	                url: apiUrl,
874	                dataType: 'json',
875	                success: function (response) {
876	                    if (!response.result.error) {
877	                        const htmlForm = response.result.html;
878	                        const $tempContainer = $('<div>').append($.parseHTML(htmlForm));
879	                        const $newFormTpl = $tempContainer.find('.lp-form-tpl');
880	
881	                        if (!$newFormTpl.length) return;
882	
883	                        $formOld.replaceWith($newFormTpl);
884	                        
885	                        $newFormTpl.find('.lp-form-tpl__title-wrapper').remove();
886	
887	                        if ($successClone && $popupElement.find('.hide-on-success').length === 0) {
888	                            $newFormTpl.before($successClone);
889	                        }
890	
891	                        s3LP.initForms($(`#_lp_block_${popupId}`));
892	                        
893	                        setTimeout(function () {
894	                            const $newForm = $popupElement.find('.lp-form-tpl');
895	                            const $targetInput = $newForm.find('input[data-alias="product_name"]');
896	
897	                            if (prodName && $targetInput.length) {
898	                                $targetInput.val(prodName);
899	                            } else {
900	                                console.warn('Имя товара или поле не найдено');
901	                            }
902	                        }, 100);
903	
904	                    } else {
905	                        console.warn('Ошибка в ответе сервера:', response.result.message);
906	                    }
907	                },
908	                error: function (xhr, status, error) {
909	                    console.error('Ошибка при получении формы:', status, error);
910	                }
911	            });
912	        });
913	    });
914	};
915
916	  
917	lpc_template.queue.folderBlock = function ($self) {
918
919		class folderMenuBlock {
920			constructor($self) {
921				var _this = this;
922				this.$block = $self;
923				this.items = null,
924				this.itemsFolderId = this.$block.find('.items-folder-id');
925				this.queryFolder = this.$block.find(`.lpc-query-folder`); // Logic query
926				this.selectFolder = this.queryFolder.find('.lpc-query-folder__select');
927				this.prefixFirstItem = "first_";
928				this.stopWord = 'top-levels';
929				
930				this.firstItem = null;
931				this.arrayItemsFolder = null;
932				if (_this.itemsFolderId.text() && _this.itemsFolderId.text() != 'not_found') {
933					this.arrayItemsFolder = this.itemsFolderId.text().split(',');
934					if (/^[A-Za-z]/.test(this.arrayItemsFolder[0])) {
935						this.firstItem = this.arrayItemsFolder[0].replace(new RegExp("^" + this.prefixFirstItem), "");
936					}
937				}
938				this.helperFunction = {
939					selectOpen() {
940						_this.queryFolder
941							.find('.lpc-query-folder__input')
942							.on('click', function (e) {
943								_this.selectFolder.toggleClass("open");
944							});
945					}
946				}
947				this.eventHandler = {
948					selected(e) {
949	
950					},
951				}
952				this.createSelectOption = async function () {
953					_this.items = await _this.getFolderFetch(() => { // get ITEMS and callback
954						_this.queryFolder.addClass('lpc-shop-not-found');
955					});
956					let dropDownList = _this.dropDownListHtml(_this.items);
957	
958					_this.queryFolder
959						.removeClass('load')
960						.addClass('loaded')
961						.find('.lpc-query-folder__body')
962						.append(dropDownList);
963	
964					let allUl = $(dropDownList).find('ul');
965					let counterItem = function (elem) {
966						$(elem).each(function (i, el) {
967							let $this = $(this);
968							let $li = $this.children('li');
969							let $div = $this.prev();
970	
971							$div.append(`<i>(${$li.length})</i>`);
972						});
973					}
974					counterItem(dropDownList);
975					counterItem(allUl);
976					return true;
977				}
978			}
979			createButton() { // создания кнопок
980				let $list = this.$block.find('.lpc-folder-menu-horizontal__list');
981	
982				let lpcMenuView = $list.attr('data-lpc-menu-view');
983				let lpcButtons = $list.attr('data-lpc-buttons');
984				let itemsFolder = this.itemsFolderId.text().split(',');
985				$list.find('.lpc-row-button').addClass('show');
986				if( itemsFolder.length < 12 ) {$list.find('.lpc-row-button').removeClass('show')}
987				let lpcRowButtonClone = $list.find('.lpc-row-button').clone();
988				$list.find('.lpc-row-button').remove()
989				
990				this.itemsFolder_length = itemsFolder.length;
991	
992				let templatesContainer = '';
993				this.items.forEach(item => {
994	
995					for (let i = 0; i < itemsFolder.length; i++) {
996						if (itemsFolder[i] == item.folder_id) {
997	
998							let link = '/' + item.alias;
999	
1000							let name = item.folder_name;
1001							let template = `<li class="lpc-folder-menu-horizontal__item ${lpcMenuView}" data-lp-selector=".lpc-folder-menu-horizontal__item" data-elem-type="container">
1002								  <a class="lpc-folder-menu-horizontal__link lp-button ${lpcButtons}" href="${link}" data-lp-selector=".lpc-folder-menu-horizontal__link" data-elem-type="text">
1003									  ${name}
1004									  <span class="lpc-folder-menu-horizontal__arrow" data-elem-type="container" data-lp-selector=".lpc-folder-menu-horizontal__arrow-line">
1005										  <span class="lpc-folder-menu-horizontal__arrow-line"></span>
1006										  <span class="lpc-folder-menu-horizontal__arrow-line"></span>
1007									  </span>
1008								  </a>
1009							  </li>`;
1010							templatesContainer += template;
1011	
1012						}
1013					}
1014				});
1015				$list.html(templatesContainer);
1016				$list.append(lpcRowButtonClone);
1017	
1018				if (!this.$block.hasClass('lpc-simple-menu')) {
1019					this.$block.addClass('lpc-row-menu');
1020					lpc_template.queue.rowMenu($('body'));
1021				}
1022	
1023			}
1024			dropDownListHtml(data) {
1025				var rootUL = document.createElement('ul');
1026				var levelObject = {};
1027				var parentLi = null;
1028				data.shift();
1029	
1030				data.forEach(item => {
1031					var li = document.createElement('li');
1032					var div = document.createElement('div');
1033					div.className = 'lpc-query-folder__option lpc-folder-item-div';
1034					div.setAttribute('data-folder_id', item.folder_id);
1035
1036					var span = document.createElement('span');
1037	
1038					function decodeHtmlEntities(input) {
1039						var doc = new DOMParser().parseFromString(input, "text/html");
1040						return doc.documentElement.textContent;
1041					}
1042					span.textContent = decodeHtmlEntities(item.folder_name);
1043					div.title = decodeHtmlEntities(item.folder_name);
1044	
1045					//var i = document.createElement('i');
1046					//i.textContent = `(${item.items})`;
1047	
1048					div.appendChild(span);
1049					//div.appendChild(i);
1050					li.appendChild(div);
1051	
1052	
1053					let level = Number(item._level);
1054	
1055					if (level == 1) {
1056						li.classList.add('first-level')
1057						rootUL.appendChild(li);
1058						parentLi = li;
1059						levelObject = {};
1060					} else {
1061						if (!levelObject[level]) {
1062							levelObject[level] = document.createElement('ul');
1063							parentLi.appendChild(levelObject[level]);
1064							parentLi.classList.add('hasChild')
1065						}
1066						levelObject[level].appendChild(li);
1067						parentLi = li;
1068					}
1069					if (this.firstItem && this.firstItem == item.folder_id) {
1070	
1071						div.classList.add('trigger_click');
1072					} else if (this.firstItem && this.firstItem == this.stopWord) {
1073						this.queryFolder.find('.all-folders').addClass('trigger_click');
1074					}
1075				});
1076	
1077				return rootUL;
1078			}
1079			async getFolderFetch(notFolder) {
1080				try {
1081					// Создаем параметры запроса
1082					let params = new URLSearchParams();
1083					params.append('param[type]', 'shop2');
1084					params.append('param[depth]', 99);
1085	
1086					// Формируем URL для GET-запроса
1087					let url = '/-/x-api/v1/public/?method=folder/getTree&' + params.toString();
1088	
1089					// Отправляем GET-запрос с использованием fetch
1090					let response = await fetch(url, {
1091						method: 'GET',
1092						headers: {
1093							'Content-Type': 'application/json'
1094						}
1095					});
1096	
1097					if (!response.ok) {
1098						throw new Error('Ошибка при выполнении запроса');
1099					}
1100	
1101					let data = await response.json();
1102	
1103					if (data.result.success) {
1104						let items = data.result.items;
1105	
1106						// Нет категории магазина
1107						if (!items.length) {
1108							notFolder();
1109							return false;
1110						}
1111	
1112						return items;
1113					}
1114				} catch (error) {
1115					console.error('Ошибка при выполнении запроса:', error);
1116					return false;
1117				}
1118			}
1119			initSelect() {
1120				let _this = this;
1121				(async function () {
1122					_this.helperFunction.selectOpen();
1123	
1124					await _this.createSelectOption();
1125	
1126					let queryFolderOption = _this.queryFolder.find('.lpc-query-folder__option'); /* option select */
1127					let folderInputSelected = _this.queryFolder.find('.lpc-query-folder__input'); /* preview BTN */
1128					let $allLi = _this.queryFolder.find('li');
1129	
1130					let flagLoadFolder = 0;
1131	
1132					queryFolderOption.on('click', function (e, trig=false) {
1133						queryFolderOption.removeClass('choose').removeClass('opted');
1134						$allLi.removeClass('active');
1135	
1136						let $this = $(this);
1137						let $li = $this.closest('li');
1138						let $ul = $li.children('ul');
1139	
1140						$this.addClass('opted');
1141	
1142	
1143						folderInputSelected.find('span').text(
1144							$this.find('span').text()
1145						);
1146	
1147						$li.addClass('active');
1148	
1149						$li.parents('.hasChild').addClass('active');
1150	
1151	
1152						var $firstLevel = _this.queryFolder.find('.first-level')
1153	
1154						let $option = $ul.children('li').children('.lpc-query-folder__option');
1155						let firstItem = '';
1156						if ($this.hasClass('all-folders')) {
1157							$option = $firstLevel.find(' > .lpc-query-folder__option');
1158							firstItem = _this.stopWord;
1159						} else {
1160							firstItem = _this.prefixFirstItem + $this.attr('data-folder_id');
1161						}
1162	
1163						$option.addClass('choose');
1164	
1165	
1166						let srtBlock = '';
1167						let len = $option.length - 1;
1168	
1169						$option.each(function (index) {
1170							let last = ',';
1171	
1172							if (index == len) {
1173								last = '';
1174							}
1175							if (index == 0) {
1176								srtBlock += firstItem + ',';
1177							}
1178							srtBlock += $(this).attr('data-folder_id') + last;
1179						});
1180	
1181						_this.itemsFolderId
1182							.text(srtBlock)
1183							.addClass('modified modified-text');
1184	
1185						_this.createButton();
1186	
1187						if(!flagLoadFolder) {
1188							_this.queryFolder.addClass('folder-selected');
1189							flagLoadFolder = 1;
1190						}
1191	
1192						// if( !trig ) {
1193						// 	_this.selectFolder.toggleClass("open");
1194						// }
1195						
1196					});
1197	
1198					if (_this.itemsFolderId.text() && _this.itemsFolderId.text() != 'not_found') {
1199						_this.createButton();
1200						_this.queryFolder.find('.trigger_click').removeClass('trigger_click').trigger('click', [true]);
1201					}
1202					
1203				})();
1204			}
1205			
1206			rowMenuItems() {
1207				let _this = this;
1208			
1209				function rowMenuItems() {
1210					let $this = _this.$block;
1211					let $menu = $this.find('.lpc-folder-menu-horizontal__list');
1212					let $toggleButton = $this.find('.lpc-folder-menu-horizontal__more');
1213		
1214					let hideText = document.querySelector('html').getAttribute('lang') === 'ru' ? 'Скрыть' : 'Hide';
1215					let currentText = document.querySelector('html').getAttribute('lang') === 'ru' ? 'Ещё' : 'Show more';
1216		
1217					let $insTextButton = $toggleButton.find('ins');
1218					let $hiddenItems = $menu.find('li:not(.lpc-folder-menu-horizontal__more):hidden');
1219					
1220					if ($hiddenItems.length) {
1221						$toggleButton.addClass('show');
1222					}
1223					
1224					$toggleButton.off('click').on('click', function () {
1225						$toggleButton.toggleClass('active');
1226						$menu.toggleClass('lpc-folder-menu-horizontal__list--show-items');
1227						$insTextButton.text($toggleButton.hasClass('active') ? hideText : currentText);
1228					});
1229				}
1230			
1231				rowMenuItems();
1232			
1233				document.addEventListener('dataMediaSourceChange', rowMenuItems);
1234			}
1235			
1236			init() {
1237				this.initSelect();
1238			}
1239		};
1240
1241		let $blocks = $self.hasClass('lpc-folder-block') ? $self : $self.find('.lpc-folder-block');
1242
1243		if ($blocks.length) {
1244
1245			$blocks.each(function () {
1246				let $block = $(this);
1247
1248				if (s3LP.is_cms) {
1249					setTimeout(()=>{
1250						var folderBlock = new folderMenuBlock($block);
1251						folderBlock.init();
1252					}, 300)
1253				}else {
1254					var folderBlock = new folderMenuBlock($block);
1255					folderBlock.rowMenuItems();
1256				}
1257			});
1258		}
1259	};
1260
1261    lpc_template.queue.lpcAjaxProduct = function($self) {
1262	  
1263        let $blocks = $self.hasClass('.lpc-ajax-product') ? $self : $self.find('.lpc-ajax-product');
1264        
1265        if ($blocks.length) {
1266        	
1267            $blocks.each(function() {
1268                let $block = $(this);
1269                
1270                var optionLpcDecor = {};
1271
1272                optionLpcDecor['columns'] = $block.attr('data-columns');
1273                optionLpcDecor['block_type'] = $block.attr('data-block-type');
1274                optionLpcDecor['img_proportions'] = $block.attr('data-img-proportions');
1275                optionLpcDecor['landing_page_mode'] = $block.attr('data-landing-page-mode');
1276                optionLpcDecor['card_block'] = $block.attr('data-card-block');
1277                optionLpcDecor['contain'] = $block.attr('data-contain');
1278                optionLpcDecor['lpc_no_image'] = $block.attr('data-lpc-no-image');
1279                optionLpcDecor['product_link_on'] = $block.attr('data-product-link-on');
1280
1281                var dataQuery = {
1282                    param: {
1283                        offset: 0,
1284                        limit: 100,
1285                        search: {
1286                            folder_id: null
1287                        },
1288                        mode: 'custom',
1289                    },
1290                    custom_products_version: 'lpc_blocks',
1291                    block_layout: 672708,
1292                    special_away: '0',
1293                    option_decor: JSON.stringify(optionLpcDecor),
1294                };
1295                
1296                lpcCreateBlockProducts(
1297					$block,
1298					dataQuery, 
1299					{
1300						beforeAjax: function(contextObject){
1301							contextObject.extenSettingBegin();
1302						},
1303						complete: function(contextObject){
1304							
1305							$block.find('.lpc_product_not_found_vv').removeClass('show');
1306							
1307							contextObject.extenSettingFinish();
1308							
1309							if(contextObject.response.result.found < 1){
1310								$block.find('.lpc_product_not_found_vv').addClass('show');
1311								$block.find('.block-id-folder').text('not_found')
1312							}
1313						}
1314					}
1315				);
1316
1317            });
1318        }
1319    };
1320	
1321	lpc_template.queue.lpcAjaxParamsProduct = function($self) {
1322
1323		let $blocks = $self.hasClass('.lpc-ajax-params-product') ? $self : $self.find('.lpc-ajax-params-product');
1324		
1325		if ($blocks.length) {
1326			$blocks.each(function() {
1327				let $block = $(this);
1328
1329
1330				let optionLpcDecor = {};
1331				optionLpcDecor['columns'] = $block.attr('data-columns');
1332				optionLpcDecor['lpc_width'] = $block.attr('data-lpc-width');
1333				optionLpcDecor['lpc_even'] = $block.attr('data-lpc-even');
1334
1335                var dataQuery = {
1336                    param: {
1337                        offset: 0,
1338                        limit: 100,
1339                        search: {
1340                            folder_id: null
1341                        },
1342                        mode: 'custom',
1343                    },
1344                    custom_products_version: 'lpc_blocks',
1345                    block_layout: 30109,
1346                    special_away: '0',
1347                    option_decor: JSON.stringify(optionLpcDecor),
1348                };
1349				lpcCreateBlockProducts(
1350					$block,
1351					dataQuery, 
1352					{
1353						complete: function(contextObject){
1354							
1355							$block.find('.lpc_product_not_found_vv').removeClass('show');
1356							
1357
1358							if(contextObject.response.result.found < 1){
1359								$block.find('.lpc_product_not_found_vv').addClass('show');
1360								$block.find('.block-id-folder').text('not_found')
1361							}
1362						}
1363					}
1364				);
1365			});
1366		}
1367	};
1368
1369	lpc_template.queue.lpcQueryProduct = function ($self) {
1370		let $blocks = $self.hasClass('lpc-shop-lot') ? $self : $self.find('.lpc-shop-lot');
1371		let initCompareFlag = false;
1372		
1373		if ($blocks.length) {
1374			
1375			/*$(document).on('click', '.lpc-shop-lot__button-buy', function(e){
1376				e.preventDefault();
1377				$(this).parent('.lpc-shop-lot-btns').find('.shop-product-btn').click();	
1378			});*/// триггер кнопки купить
1379			$(document).on('click', '.lpc-shop-lot__button', function(e) {
1380	
1381				var $this = $(this),
1382					$form = $this.closest('form'),
1383					form = $form.get(0),
1384					adds = $form.find('.additional-cart-params'),
1385					len = adds.length,
1386					i, el,
1387					a4 = form.amount.value,
1388					kind_id = form.kind_id.value;
1389			
1390		
1391					if (shop2.my.gr_new_notification) {
1392						// Находим картинку товара
1393						var $image = $form.find('.gr-product-image--js');
1394					}
1395				e.preventDefault();
1396		
1397				if (len) {
1398					a4 = {
1399						amount: a4
1400					};
1401		
1402					for (i = 0; i < len; i += 1) {
1403						el = adds[i];
1404						if (el.value) {
1405							a4[el.name] = el.value;
1406						}
1407					}
1408				}
1409				
1410				lpc_template.queue.lpcAddCard.add(kind_id, a4, function(d) {
1411					$('#shop2-cart-preview').replaceWith(d.data);
1412					
1413					var totalCartAmount = +$(d.data).find('.gr-cart-total-amount').text();
1414					var totalCartSum = $(d.data).find('.gr-cart-total-sum').data('total-price');
1415					
1416					if (totalCartAmount>0) {
1417						$('.head-cart__btn').removeClass('pointer_events_none');
1418						$('.gr-cart-total-amount').text(totalCartAmount);
1419						$('.gr-cart-total-sum ins').text(totalCartSum);
1420					} else{
1421						$('.mosaic-shop2-cart-preview__total-count').text('0'); // 1935 04.12.2024 внес правку для 140 шаблона. при покупке из попап карточки товара лпц, не обновлялась маленькая корзина 
1422						$('.gr-cart-total-amount').text('0');
1423						$('.gr-cart-total-sum ins').text('0');
1424					};
1425					
1426					if (d.errstr) {
1427						if (shop2.my.gr_new_notification) {
1428		
1429							shop2.popupNotification({
1430								"itemContent": d.errstr, 
1431								"itemClass": "gr-notification__item--purchase",
1432							});
1433						} else {
1434							shop2.msg(d.errstr, $this);
1435						}
1436					} else {
1437						var $text = window._s3Lang.JS_SHOP2_ADD_CART_WITH_LINK;
1438						//var $text = $text.replace("</a>", "<i><svg class='gr-svg-icon'><use xlink:href='#icon_shop_notify_arr'></use></svg></i></a>");
1439						
1440						if (shop2.my.gr_new_notification) {
1441		
1442							// Выводим сообщение пользователю
1443							/*shop2.popupNotification({
1444								"itemContent": $text, 
1445								"itemClass": "gr-notification__item--purchase",
1446								"itemImage": shop2.my.gr_hide_msg_image ? false : true,
1447								"itemSrc": $image.find('img').attr('src'),
1448								"itemHref": $image.data('product-href') || $image.find('a').attr('href'),
1449								"itemContain": $image.data('image-view'),
1450								"itemSize": $image.data('image-size'),
1451							});*/
1452						} else {
1453							shop2.msg($text.replace("%s", shop2.uri + "/cart"), $this);
1454						}
1455						
1456						shop2.on('afterCartAddItem', function(res, status) {
1457					       /* const productPreviewPopup = $('.remodal[data-remodal-id="card-preview-remodal"]');
1458					        
1459					        shop2.msg($text.replace("%s", shop2.uri + "/cart"), $this);*/
1460					    });
1461					}
1462		
1463					if (d.panel) {
1464						$('#shop2-panel').replaceWith(d.panel);
1465					};
1466				});
1467			});	
1468			
1469			if(!s3LP.is_cms){
1470				$(document).keyFilter('.lpc-product-amount input:text', {
1471			        type: shop2.options.amountType
1472			    });
1473			}
1474			
1475			$(document).on('click', '.lpc-product-amount-btn.lpc-amount-minus', function() {
1476		          var $this = $(this),
1477		              text = $this.siblings('input:text'),
1478		              value = text.getVal(),
1479		              amount_min = parseFloat(text.data('min')),
1480		              multiplicity = parseFloat(text.data('multiplicity'));
1481		  
1482		          if (value) {
1483		              value = value[0];
1484		          }
1485		  
1486		          if (amount_min && value <= amount_min) {
1487		              return;
1488		          }
1489		  
1490		          value = checkAmount(value, amount_min, multiplicity, -1);
1491		          
1492		          if (amount_min > 0) {
1493		            if (value <= amount_min) {
1494		                value = amount_min;
1495		            }
1496		          } else {
1497		            if (value <= shop2.options.amountDefaultValue) {
1498		               value = shop2.options.amountDefaultValue;
1499		            }
1500		          }
1501		          
1502		          
1503		          
1504		          text.val(value);
1505		          text.trigger('change');
1506		      });
1507		      $(document).on('click', '.lpc-product-amount-btn.lpc-amount-plus', function() {
1508		          var $this = $(this),
1509		              text = $this.siblings('input:text'),
1510		              value = text.getVal(),
1511		              amount_min = parseFloat(text.data('min')),
1512		              multiplicity = parseFloat(text.data('multiplicity'));
1513		            
1514		          if (value) {
1515		              var value = value[0];
1516		          }			  
1517		          
1518		          var value = checkAmount(value, amount_min, multiplicity, 1);
1519		          text.val(value);
1520		          text.trigger('change');
1521		    });
1522			function checkAmount(amount, amount_min, multiplicity, sign) {
1523
1524	          if (multiplicity > 0) {
1525	              amount += multiplicity * sign;
1526	          } else {
1527	              amount += shop2.options.amountDefaultInc * sign;
1528	          }
1529	          
1530	          amount = amount.toFixed(2) - 0;
1531	
1532	          return amount
1533	      	}
1534			
1535			$blocks.each(function() {
1536
1537                let $block = $(this);
1538                let $blockList = $block.find('.lpc-query-products');
1539				
1540				let optionLpcDecor = {};
1541				optionLpcDecor['block-lot-id'] = $blockList.attr('data-lots-block-id');
1542				optionLpcDecor['on_lg'] = $blockList.attr('data-on-lg');
1543				optionLpcDecor['columns'] = $blockList.attr('data-columns');
1544				optionLpcDecor['block_type'] = $blockList.attr('data-block-type');
1545				optionLpcDecor['img_proportions'] = $blockList.attr('data-img-proportions');
1546				optionLpcDecor['landing_page_mode'] = $blockList.attr('data-landing-page-mode');
1547				optionLpcDecor['card_block'] = $blockList.attr('data-card-block');
1548				optionLpcDecor['product_mode'] = $blockList.attr('data-product-mode');
1549				optionLpcDecor['contain'] = $blockList.attr('data-contain');
1550				optionLpcDecor['lpc_no_image'] = $blockList.attr('data-lpc-no-image');
1551				optionLpcDecor['lpc_view_show_option'] = $blockList.attr('data-lpc-view-show-options');
1552				optionLpcDecor['lpc_view_vendor'] = $blockList.attr('data-lpc-view-vendor');
1553				optionLpcDecor['lpc_view_rating'] = $blockList.attr('data-lpc-view-rating');
1554				optionLpcDecor['lpc_view_article'] = $blockList.attr('data-lpc-view-article');
1555				optionLpcDecor['lpc_view_annonce'] = $blockList.attr('data-lpc-view-annonce');
1556				optionLpcDecor['lpc_view_sale'] = $blockList.attr('data-lpc-view-sale');
1557				optionLpcDecor['lpc_view_amount_flag'] = $blockList.attr('data-lpc-view-amount-flag');
1558				optionLpcDecor['lpc_view_buy_btn'] = $blockList.attr('data-lpc-view-buy-btn');
1559				optionLpcDecor['lpc_view_amount'] = $blockList.attr('data-lpc-view-amount');
1560				optionLpcDecor['lpc_view_one_click'] = $blockList.attr('data-lpc-view-one-click');
1561
1562
1563				var dataQuery = {
1564					param: {
1565						search: {
1566							folder_id: null
1567						},
1568						mode: 'custom',
1569						limit: 36
1570					},
1571					custom_products_version: 'lpc_blocks',
1572					block_layout: '134709',
1573					special_away: '1',
1574					lpc_lot_products_option: '1',
1575					'option_decor': JSON.stringify(optionLpcDecor),
1576				};
1577				
1578				
1579				
1580				$(document).on('click', '.lpc-options-more', function(){
1581					if(optionLpcDecor['block-lot-id'] == $(this).closest('.lpc-shop-lot').attr('id')) {
1582						$(this).toggleClass('active');
1583						$(this).siblings('.lpc-options-container').slideToggle();
1584					}
1585				});
1586			
1587				$(document).on('click', '.lpc-shop-lot__image', function(e){
1588					if(optionLpcDecor['block-lot-id'] == $(this).closest('.lpc-shop-lot').attr('id')) {
1589						if ($(this).hasClass('lpc-shop-lot__image-transition')) {
1590							return;
1591						}
1592						e.preventDefault();
1593						$(this).closest('.lpc-shop-lot__inner').find(".lpc-shop-lot__quick-trigger").trigger('click');
1594					}
1595				});// клик на картинку
1596				
1597				$(document).on('click', '.lpc-product-compare-custom-text', function(e){
1598					if(optionLpcDecor['block-lot-id'] == $(this).closest('.lpc-shop-lot').attr('id')) {
1599						$(this).siblings('.lpc-product-compare').trigger('click');	
1600					}
1601				});
1602				
1603
1604				let observer = new IntersectionObserver((entries, observer) => {
1605				    entries.forEach(entry => {
1606				        if (entry.isIntersecting) {
1607				            // Если для этого блока данные уже загружены, повторно не выполняем запрос
1608				            if ($block.data('loaded')) return;
1609				
1610				            lpcCreateBlockProducts(
1611				                $block,
1612				                dataQuery, 
1613				                {
1614				                    beforeAjax: function(contextObject) {
1615				                        contextObject.extenSettingBegin();
1616				                    },
1617				                    complete: function(contextObject) {
1618				
1619				                        if (!s3LP.is_cms) {
1620				                            shop2.trigger('afterProductsLazyLoaded');
1621				                        }
1622				                        
1623				                        if (!s3LP.is_cms) {
1624				                            if (!initCompareFlag) {
1625				                                contextObject.getCompare($blockList);
1626				                                initCompareFlag = true;
1627				                            }
1628				                        }
1629				
1630				                        contextObject.extenSettingFinish();
1631				
1632				                        $('.lpc-shop-lot__popup-back, .lpc-shop-lot__popup-close').on('click', function(){
1633				                            $(".lpc-shop-lot__popup").removeClass('active');
1634				                            $("html").removeClass('lpc-shop-popup-scroll');
1635				                        });
1636				                        
1637				                        if ($('.lpc-shop-lot__list-check-mobile').length){ 
1638				                            $(window).on("resize", function () {
1639				                                setTimeout(function() {
1640				                                    var mediaTypeCheck = $('.decor-wrap').attr('data-media-source');
1641				                                    if (mediaTypeCheck == "media-xs") {
1642				                                        $('.lpc-shop-lot__list-check-mobile').addClass('lpc-card--type-1');
1643				                                    } else {
1644				                                        $('.lpc-shop-lot__list-check-mobile').removeClass('lpc-card--type-1');
1645				                                    }
1646				                                }, 200);
1647				                            }).trigger("resize");
1648				                        }
1649				                        
1650				                        $('.lpc-shop-lot__popup .lpc-shop-lot__image').on('click', function(e){
1651				                            e.preventDefault();
1652				                        });
1653				                        
1654				                        contextObject.receivingDataPopup();
1655				                    }
1656				                }
1657				            );
1658				
1659				            // Помечаем блок как загруженный, чтобы избежать повторного запроса
1660				            $block.data('loaded', true);
1661				
1662				            // Прекращаем наблюдение за этим блоком
1663				            observer.unobserve(entry.target);
1664				        }
1665				    });
1666				}, { rootMargin: "200px 0px", threshold: 0.1 });
1667				
1668				// Предполагается, что $block — jQuery-объект, поэтому передаем DOM-элемент:
1669				observer.observe($block[0]);
1670
1671			});
1672		}
1673	};
1674
1675	if ($('.s3-preloader').length) {
1676		s3PreloaderMutation($('.s3-preloader')[0]);
1677	};
1678	
1679	/*lpc_template.queue.newYear = function($self) { // НЕ УДАЛЯТЬ - НГ оформление
1680		if (!!document.querySelector('#lp_constructor')) {
1681			let lpcSnow = `<div id="lpc-snow-block" class="sky"></div>`;
1682			let newYearTpl = `<div class="lpc-new-year">
1683				<ul class="lpc-new-year__items">
1684					<li></li>
1685					<li></li>
1686					<li></li>
1687					<li></li>
1688					<li></li>
1689					<li></li>
1690					<li></li>
1691				</ul>
1692				<ul class="lpc-new-year__items">
1693					<li></li>
1694					<li></li>
1695					<li></li>
1696					<li></li>
1697					<li></li>
1698					<li></li>
1699					<li></li>
1700					<li class="first_red_toy"></li>
1701					<li class="green_toy"></li>
1702				</ul>
1703				<ul class="lpc-new-year__items second_items">
1704					<li></li>
1705					<li></li>
1706					<li></li>
1707					<li></li>
1708					<li></li>
1709					<li></li>
1710					<li></li>
1711					<li class="red_toy"></li>
1712				</ul>
1713				<ul class="lpc-new-year__items">
1714					<li></li>
1715					<li></li>
1716					<li></li>
1717					<li></li>
1718					<li></li>
1719					<li></li>
1720					<li></li>
1721					<li class="last_green_toy"></li>
1722				</ul>
1723				<ul class="lpc-new-year__items">
1724					<li></li>
1725					<li></li>
1726					<li></li>
1727					<li></li>
1728					<li></li>
1729					<li></li>
1730					<li></li>
1731				</ul>
1732			</div>`;
1733		
1734			if (!!document.querySelector('#lp_constructor') && !$('.lpc-new-year__items').length) {
1735				$('#landing_page_controls').append(newYearTpl);
1736				//$('#landing_page_site').append(newYearTpl);
1737				$('#landing_page_controls').append(lpcSnow);
1738
1739				if (readCookie('lpc_disable_snow') != '1') {
1740					letItSnow();
1741				};
1742			};
1743		
1744			let $snow = $('#lpc-snow-block');
1745			
1746			const config = {
1747				attributes: true
1748			};
1749		
1750			const callback = function (mutationsList, observer) {
1751				
1752				for (let mutation of mutationsList) {
1753					if (!$(target).hasClass('hidden')) {
1754						
1755						$('#lp_constructor').addClass('opened');
1756						$snow.appendTo($('#landing_page_controls'));
1757						
1758					} else {
1759						
1760						$('#lp_constructor').removeClass('opened');
1761						$snow.appendTo($('#landing_page_site'));
1762						
1763					}
1764
1765					if (!$(target2).is(':hidden')) {
1766						$('._live._live--lp ._live__header').addClass('hide_live_header');
1767					} else {
1768						$('._live._live--lp ._live__header').removeClass('hide_live_header');
1769					}
1770				}
1771			};
1772		
1773			let target = document.querySelector('.folders-menu-wrapper');
1774			let target2 = document.querySelector('.block-css-controls');
1775		
1776			const observer = new MutationObserver(callback);
1777			const observer2 = new MutationObserver(callback);
1778		
1779			observer.observe(target, config);
1780			observer2.observe(target2, config);
1781		};
1782	};*/
1783
1784	
1785	lpc_template.queue.lpcWatchPreloader = function($self) {
1786		s3PreloaderMutation($('.decor-wrap')[0]);
1787	};
1788
1789	lpc_template.queue.checkBgImg = function ($self) {
1790		$('.lp-block-bg._photo_avaiable').each(function(){
1791			var bgWh = $(this).css('background-image');
1792			
1793			if(bgWh != "none") {
1794				$(this).addClass('_there-photo');
1795			}
1796		})
1797	};
1798  
1799
1800  	lpc_template.queue.lpcAboutPopupLink  = function($self) {
1801		
1802	    document.addEventListener('lpcPopupFormInitDone', function(){
1803	      $('a[href^="popup:"]').removeClass('lpc_pointer_events_none');
1804	    });
1805	};
1806	
1807	lpc_template.queue.lpcSharePopupBtn  = function($self) {
1808		var $block = $self.find('.lpc-share-1');
1809			
1810		if ($block.length && $block.find('.lpc-share-1__button').length) {	
1811				$('.lpc-share-1__button').each(function(){
1812					var $shareItems = $(this).parents('.lpc-share-1').find(".ya-share2__popup"),
1813						$sharePopup = $(this).parents('.lpc-share-1').find(".lpc-share-1__popup"),
1814						$sharePopupParent = $(this).parents('.lpc-share-1').find(".ya-share2_custom"),
1815						$buttonWidth = $(this).parents('.lpc-share-1').find(".lpc-share-1__button").outerWidth();
1816						
1817						
1818					$shareItems.clone().appendTo($sharePopup);
1819					$sharePopupParent.css('width', $buttonWidth);
1820				});
1821			
1822			
1823			$doc.on("click", function (e) {
1824				if (!$(e.target).closest($('.lpc-share-1__button')).length && !$(e.target).closest($('.ya-share2_custom')).length) {
1825					$doc.find(".lpc-share-1__popup").removeClass("_opened");
1826				};
1827			});
1828			
1829			$('.lpc-share-1__button').on('click', function(){
1830				if($(this).closest('.lpc-share-1__wrap').find('.lpc-share-1__popup').hasClass('_opened')){
1831					$(this).closest('.lpc-share-1__wrap').find('.lpc-share-1__popup').removeClass('_opened');
1832				}else {
1833					$('.lpc-share-1__popup._opened').removeClass('_opened');
1834					$(this).closest('.lpc-share-1__wrap').find('.lpc-share-1__popup').addClass('_opened');
1835				}
1836				
1837				var popupHeight = $(this).closest('.lpc-share-1__wrap').find('.ya-share2_custom .ya-share2__popup').height();
1838			});
1839		}
1840	};
1841	
1842	lpc_template.queue.lpcAddCard = {
1843		add: function(kind_id, a4, func) {
1844
1845		    shop2.trigger('beforeCartAddItem');
1846		
1847		    $.post(
1848		      '/-/shop2-api/?cmd=cartAddItem', {
1849		        hash: shop2.apiHash.cartAddItem,
1850		        ver_id: shop2.verId,
1851		        kind_id: kind_id,
1852		        amount: a4
1853		      },
1854		      function(d, status) {
1855		        shop2.fire('afterCartAddItemLpc', func, d, status);
1856		        shop2.trigger('afterCartAddItemLpc', d, status);
1857		      },
1858		      'json'
1859		    );
1860		}
1861	};
1862
1863	
1864	lpc_template.queue.lpcCompare = {
1865	    add: function(kind_id, callback) {
1866	      this.action('add', kind_id, callback);
1867	    },
1868	    remove: function(kind_id, callback) {
1869	      this.action('del', kind_id, callback);
1870	    },
1871	    clear: function(callback) {
1872	      this.action('clear', null, callback);
1873	    },
1874	    action: function(action, kind_id, func) {
1875	
1876	      var eventName = $.camelCase('Compare-' + action);
1877	
1878	      shop2.trigger('before' + eventName);
1879	
1880	      $.post(
1881	        '/-/x-api/v1/public/?method=shop2/compare', {
1882	        	kind_id,
1883		        action,
1884				lpc_block_compare: "1",
1885	        },
1886	        function(d, status) {
1887	          shop2.fire('after' + eventName, func, d.result, status);
1888	          shop2.trigger('after' + eventName, d.result, status);
1889	        }
1890	      );
1891	    }
1892	};
1893	
1894	lpc_template.queue.menuSimplePopup = function($self) {
1895		
1896		var $block = $self.hasClass('js-menu-wrap') ? $self : $self.find('.js-menu-wrap');
1897		
1898		$block.each(function(){
1899			var $this = $(this),
1900				$topMenuWrap = $this.find('.js-menu__wrap'),
1901				$menu = $this.find('.js-menu_appedable'),
1902				$burger = $this.find('.js-burger'),
1903				$popup = $this.find('.js-popup'),
1904	    		popupHeight = $(window).height() - $this.height(),
1905	    		menuHeight = $this.outerHeight(),
1906	    		popupTop = menuHeight < 0 ? 0 : menuHeight,
1907	    		popupTop = s3LP.is_cms ? popupTop + 72 : popupTop,
1908	    		$bgTop = $this.height() + 50 < 0 ? 0 : $this.height() + 50,
1909	    		$bgTop = s3LP.is_cms ? $bgTop + 72 : $bgTop,
1910	    		$liHaschild = $this.find('.haschild');
1911    		
1912    		$this.find('.lp-menu-block-bg').animate({top: $bgTop}, 400);
1913	    	
1914	    	$popup.css('top', popupTop);
1915	    		
1916			$menu.clone().prependTo($topMenuWrap);
1917			
1918			$(this).append('<div class="lp-menu-block-bg"></div>');
1919			
1920			function menuShow() {
1921		        var $ulWidth = 0,
1922		            $ulWrapWidth = $this.find('.js-menu__wrap').width();
1923		
1924		        $($menu).children('li').each(function(){
1925		            var $width = $(this).children('a').outerWidth(true);
1926		            $ulWidth += $width;
1927		        });
1928		        
1929		        if (window.matchMedia('(min-width : 960px)').matches) {
1930		        	if ($ulWidth < $ulWrapWidth) {
1931		        		$this.find('.js-menu__wrap').addClass('show');
1932		        		$this.find('.js-burger').hide();
1933		        	}
1934		        	else {
1935		        		$this.find('.js-menu__wrap').removeClass('show');
1936		        		$this.find('.js-burger').show();
1937		        	}
1938		        } else if (window.matchMedia('(max-width : 959px)').matches && $menu.find('li').length == 0) {
1939					$this.find('.js-menu__wrap').addClass('show');
1940				    $this.find('.js-burger').hide();
1941					
1942				} else if (window.matchMedia('(max-width : 959px)').matches) {
1943		    		$this.find('.js-menu__wrap').removeClass('show');
1944		    		$this.find('.js-burger').show();
1945		        }
1946		        
1947		        var $bgTop = $this.offset().top + $this.height();
1948		        
1949		        menuHeight = $this.outerHeight(),
1950	    		popupTop = menuHeight < 0 ? 0 : menuHeight,
1951	    		popupTop = s3LP.is_cms ? popupTop + 72 : popupTop,
1952	    		$bgTop = $this.height() < 0 ? 0 : $this.height(),
1953	    		$bgTop = s3LP.is_cms ? $bgTop + 72 : $bgTop;
1954	    		
1955	    		$this.find('.lp-menu-block-bg').animate({top: $bgTop}, 400);
1956	    		
1957    			$popup.css('top', popupTop);
1958	    		
1959	    		$this.find('.lp-menu-block-bg').css('top', $bgTop);
1960			}
1961			
1962		    $(window).on('resize', function(){
1963		    	
1964	    		setTimeout(function(){
1965					menuShow();
1966	    		},500);
1967	    		
1968		    }).trigger('resize');
1969		
1970		    $burger.on('click', function(){
1971		    	$menu.find('li a').addClass('menu-popup-item-custom');
1972		    	if ($(this).hasClass('_in-side')) {
1973		    		$popup.animate({top: 0}, 400);
1974		    		$this.find('.lp-menu-block-bg').css('top', 0);
1975		    	}
1976		    	if (!$(this).hasClass('_in-side')) {
1977			    	if (s3LP.is_cms) {
1978			    		$('html, body').animate({
1979						    scrollTop: $this.offset().top - 72
1980						}, 100);
1981			    	}
1982			    	else {
1983			    		$('html, body').animate({
1984						    scrollTop: $this.offset().top
1985						}, 100);
1986			    	}
1987		    	}
1988		    	
1989		    	$popup.find('.js-popup__inner').css({
1990		    		'overflow' : '',
1991		    		'max-height' : '100%'
1992		    	});
1993		    	
1994		    	$burger.toggleClass('opened');
1995		    	if ($popup.hasClass('opened')) {
1996		    		$popup.animate({height: "0%"}, {duration: 800, complete: function() {$this.css('z-index', '')}}).removeClass('opened');
1997		    		$this.find('.lp-menu-block-bg').fadeOut(600);
1998		    		
1999		    		$('html').css('overflow', '');
2000		    	}
2001		    	else {
2002		    		$popup.animate({height: popupHeight}, {duration: 800}).addClass('opened');
2003		    		$this.find('.lp-menu-block-bg').fadeIn(600);
2004		    		$this.css('z-index', '999')
2005		    		$('html').css('overflow', 'hidden');
2006		    	}
2007		    });
2008	    	
2009		    $this.find('.haschild').on('click', function(e){
2010		    	e.stopPropagation();
2011		    	$(this).toggleClass('_open').children('ul').slideToggle();
2012		    });
2013		    
2014		    $popup.find('.js-menu_appedable').on('click', 'a', function(){
2015		    	$burger.toggleClass('opened');
2016		    	$popup.animate({height: "0%"}, 800).removeClass('opened');
2017	    		$this.find('.lp-menu-block-bg').fadeOut(600);
2018	    		$this.css('z-index', '');
2019	    		$('html').css('overflow', '');
2020		    });	
2021		    
2022		    if (s3LP.is_cms && typeof LpController !== 'undefined') {
2023				setTimeout(function(){
2024					LpController.afterSave(function () {
2025						menuShow();
2026						setTimeout(function(){
2027					    	$(window).trigger('resize');
2028						},500);
2029					});
2030				},2000);
2031			}
2032		});
2033	}
2034  
2035  	lpc_template.queue.fpInit = function($self) {
2036		var $block = $self.find('.js-lp-fastpay');
2037		
2038		if ($block.length) {
2039	
2040			$block.on('click', '.js-fp-show-form', function(e) {
2041				e.preventDefault();
2042	
2043				var $this = $(this),
2044					$parent = $this.closest('.js-lp-fastpay'),
2045					//$currentParent = $this.parents('.lp-payment-service-item'),
2046					//currentPrice = $currentParent.find('.lp-payment-service-item_price').html(),
2047					needHref = $parent.data('page-path'),
2048					serviceID = $this.data('service-id'),
2049					fastPayID = $this.closest('.lp-payment-service-item').attr('data-fastpay-id');
2050					
2051					$this.addClass('_opened');
2052					
2053				$.ajax({
2054					url: '/-/x-api/v1/public/?method=fastpay/getService&param[service_id]='+serviceID+'&param[fast_pay_id]='+ fastPayID +'&param[tpl]=global:lpc4.fast_payment.tpl',
2055					success: function(data) {
2056						var htmlForm = data.result.html;
2057						var $newBlock = $this.closest('.lp-payment-service-item').append(htmlForm);
2058						//let $btn = $currentParent.find('.lp-form-tpl__button-wrapper .lp-button');
2059						
2060						//$btn.text($btn.text() + ' ' + currentPrice);
2061						
2062						
2063						s3LP.initForms($newBlock);
2064						$this.closest('.lp-payment-service-item').find('.lp-payment-service-item_button').hide();
2065						var needAttr = $self.find('.lp-payment__form').attr('data-api-url') + "&param[href]=" + needHref;
2066						$newBlock.find('.lp-payment__form').attr('data-api-url', needAttr);
2067						$newBlock.find('.lp-payment__form').data('api-url', needAttr);
2068						$this.closest('.lp-payment-service-item').find('.payment-selection:first').addClass('_active');
2069					}
2070				});
2071				
2072			});
2073	
2074			$block.find('.fp_free_wrap').each(function() {
2075				var $this = $(this).find('.js-lp-fp-form'),
2076					$parent = $this.closest('.js-lp-fastpay'),
2077					needHref = $parent.data('page-path'),
2078					needAttr = $this.attr('data-api-url') + "&param[href]=" + needHref;
2079		
2080				$this.attr('data-api-url', needAttr);
2081				$this.data('api-url', needAttr);
2082		
2083			});
2084			
2085			$block.on('click', '.payment-selection-in', function(e) {
2086				$(this).each(function () {
2087					e.preventDefault();
2088					$(this).parent('.payment-selection').siblings('.payment-selection').removeClass('_active');
2089					$(this).parent('.payment-selection').addClass('_active');
2090					$(this).siblings('.type-radio-payment').click();
2091				});
2092			});
2093		}
2094		
2095		
2096	};
2097	
2098	lpc_template.queue.donationsBlock = function($self) {
2099		let $block = $self.find('.lpc-payment-block-2');
2100		
2101		if (!s3LP.is_cms) {
2102			$block.each(function(){
2103				let $this = $(this);
2104				let $price = $this.find('.lp-payment__form .lp-form-tpl__item:first-of-type').addClass('custom_price_input');
2105    
2106			    let $email = $this.find('.lp-payment__form input[name="email"]').val('[email protected]');
2107			    let $phone = $this.find('.lp-payment__form input[name="phone"]').val('+1234567890');
2108			    
2109			    $price.find('input[name="price"]').val($block.find('.lpc_payment_buttons_js .lpc-button--type-1').text().replace(/\D/g, ''));
2110
2111				$this.find('.lpc_payment_buttons_js .lp-button').on('click', function(){
2112			        let currentValue = $(this).text().replace(/\D/g, '');
2113			        
2114			        $this.find('.lpc_payment_buttons_js .lp-button').removeClass('lpc-button--type-1').addClass('lpc-button--type-2');
2115			        $(this).removeClass('lpc-button--type-2').addClass('lpc-button--type-1');
2116			        
2117			        if ($(this).hasClass('custom_price_btn')) {
2118			            $price.fadeIn(200);
2119			            $this.find('input[name="price"]').val('').focus();
2120			        } else {
2121			            $this.find('input[name="price"]').val(currentValue);
2122			            $price.hide();
2123			        };
2124				});
2125			});
2126		}
2127	};
2128	
2129	lpc_template.queue.geoLinkInit = function($self){
2130		let $block = $self.find('.lpc-contact-1');
2131		
2132		
2133		if($block.length) {
2134			
2135			/*var htmlLang = document.documentElement.lang;
2136				var script = document.createElement("script");
2137				script.async = "async";
2138			if (htmlLang == "en") {
2139				if (keyMap != "") {
2140					script.src = `//api-maps.yandex.ru/2.1/?apikey=${keyMap}&lang=en_RU`;
2141				} else {
2142					script.src = `//api-maps.yandex.ru/2.1/?lang=en_RU`;
2143				}
2144			} else {
2145				if (keyMap != "") {
2146					script.src = `//api-maps.yandex.ru/2.1/?apikey=${keyMap}&lang=ru_RU`;
2147				} else {
2148					script.src = `//api-maps.yandex.ru/2.1/?lang=ru_RU`;
2149				}
2150			}
2151			*/
2152			document.addEventListener('click', function(e) {
2153			
2154			    const link = e.target.closest('.ymaps-geolink-click');
2155			    const allGeoAddresses = document.querySelectorAll('.lpc-contact-1__geo-address');
2156			    const allMapContainers = document.querySelectorAll('.lpc-geolink-single-map');
2157			
2158			    // === 1. Закрываем все карты при клике вне адреса или карты ===
2159			    if (!link) {
2160			        let clickedInside = false;
2161			        allGeoAddresses.forEach(el => { if (el.contains(e.target)) clickedInside = true; });
2162			        allMapContainers.forEach(el => { if (el.contains(e.target)) clickedInside = true; });
2163			
2164			        if (!clickedInside) {
2165			            allMapContainers.forEach(c => c.style.display = 'none');
2166			        }
2167			        return;
2168			    }
2169			
2170			    // === 2. Открываем нужную карту ===
2171			    const containerId = link.getAttribute('data-map-container');
2172			    if (!containerId) return;
2173			
2174			    const container = document.querySelector(containerId);
2175			    const mapDiv = container.querySelector('div[id^="lpc-yandex-map-"]');
2176			    if (!mapDiv) return;
2177			
2178			    // Закрываем все другие карты
2179			    allMapContainers.forEach(c => { if (c !== container) c.style.display = 'none'; });
2180			
2181			    // Тоггл
2182			    if (container.style.display === 'block') {
2183			        container.style.display = 'none';
2184			        return;
2185			    }
2186			
2187			    container.style.display = 'block';
2188			
2189			
2190			    if (!container.dataset.mapInitialized) {
2191			        ymaps.ready(function() {
2192			            // Парсим координаты из data-bounds
2193			            let coords = [55.755826, 37.6173];
2194			            try {
2195			                const b = link.getAttribute('data-bounds') || '';
2196			                const nums = b.replace(/[\[\]]/g, '').split(',').map(parseFloat);
2197			                if (nums.length >= 2) coords = [nums[0], nums[1]];
2198			            } catch(e) {}
2199			
2200			            const map = new ymaps.Map(mapDiv.id, {
2201			                center: coords,
2202			                zoom: 14,
2203			                controls: ['zoomControl']
2204			            });
2205			
2206			            // Метка
2207			            const placemark = new ymaps.Placemark(coords, {
2208			                hintContent: link.textContent.trim(),
2209			                balloonContent: link.getAttribute('data-description') || link.textContent.trim()
2210			            }, {
2211			                preset: 'islands#redDotIconWithCaption'
2212			            });
2213			            map.geoObjects.add(placemark);
2214			            if (link.getAttribute('data-description')) placemark.balloon.open();
2215			
2216			            
2217			
2218			            routeButton.events.add('click', function () {
2219			                // Определяем точку "откуда" — либо геолокация, либо центр города
2220			                if (navigator.geolocation) {
2221			                    navigator.geolocation.getCurrentPosition(pos => {
2222			                        const userCoords = [pos.coords.latitude, pos.coords.longitude];
2223			                        openRoute(userCoords, coords);
2224			                    }, () => {
2225			                        // Если геолокация запрещена — от центра Москвы
2226			                        openRoute([55.7558, 37.6176], coords);
2227			                    });
2228			                } else {
2229			                    openRoute([55.7558, 37.6176], coords);
2230			                }
2231			            });
2232			
2233			            // Функция открытия маршрута в новой вкладке
2234			            function openRoute(from, to) {
2235			                const url = `https://yandex.ru/maps/?rtext=${from[0]},${from[1]}~${to[0]},${to[1]}&rtt=auto`;
2236			                window.open(url, '_blank');
2237			            }
2238			
2239			            // Добавляем кнопку на карту (внизу по центру)
2240			            map.controls.add(routeButton, {
2241			                float: 'none',
2242			                position: { bottom: 15, left: '50%', transform: 'translateX(-50%)' }
2243			            });
2244			
2245			            // Включаем GeolinkControl (чтобы повторные клики работали)
2246			            ymaps.modules.require(['control.GeolinkControl'], function(GeolinkControl) {
2247			                map.controls.add(new GeolinkControl({ selector: '[data-map-container="' + containerId + '"]' }));
2248			            });
2249			
2250			            container.dataset.mapInitialized = '1';
2251			        });
2252			    }
2253			});
2254		}
2255	};
2256	
2257
2258  lpc_template.queue.popupTouch = function(){
2259  	$('a[href^="popup:"]').on('click', function (){
2260  		setTimeout(function() {
2261  			lpc_template.popupAdaptiveBlock();
2262  			
2263  			document.dispatchEvent(new Event(`lpcPopupOpened`, {bubbles: true}));
2264  			
2265  			if ($('.lp-popup-wrapper form').find('input[data-alias=product_name]').val() == ""){
2266  				$('.lp-popup-wrapper form').find('input[data-alias=product_name]').val("Форма");
2267  			}
2268  		 }, 80);
2269  	})
2270  };
2271  
2272  lpc_template.queue.popupTouchClose = function(){
2273  	$('.js-close-popup').bind('click', function(event){
2274	})
2275  };
2276
2277  const adaptiveBlockEvent = new Event('dataMediaSourceChange');
2278  window.adaptiveBlockEvent = adaptiveBlockEvent; // сделано чтобы была возможность дергать скрипт, для сайтов с версией для слабовидящих
2279  
2280  if ($('.color-theme a').length > 0) {
2281	  $(document).on('click', '.color-theme a', function(){
2282			setTimeout(function(){
2283				document.dispatchEvent(adaptiveBlockEvent);
2284			}, 100);
2285	  }); // исправление переключение цвета в старой версии для слабовидящих https://staff.megagroup.ru/staff/sites/?site_id=1085232
2286  }
2287
2288  checkMediaSource = function(media) {
2289    if(lpc_template.media_source != media) {
2290      lpc_template.media_source = media;
2291      document.dispatchEvent(adaptiveBlockEvent);
2292    }
2293  }
2294  
2295
2296  lpc_template.adaptiveBlock = function () {
2297
2298    let decorWrap = document.querySelector(".decor-wrap");
2299
2300    if(decorWrap) {
2301    	
2302    let decorWrapWidth = decorWrap.offsetWidth;
2303      if (decorWrapWidth < 480) {
2304        decorWrap.setAttribute("data-media-source", "media-xs");
2305        checkMediaSource('media-xs');
2306      } else if (decorWrapWidth < 768) {
2307        decorWrap.setAttribute("data-media-source", "media-sm");
2308        checkMediaSource('media-sm');
2309      } else if (decorWrapWidth < 992) {
2310        decorWrap.setAttribute("data-media-source", "media-md");
2311        checkMediaSource('media-md');
2312      } else if (decorWrapWidth < 1280) {
2313        decorWrap.setAttribute("data-media-source", "media-lg");
2314        checkMediaSource('media-lg');
2315      } else if (decorWrapWidth >= 1280) {
2316        decorWrap.setAttribute("data-media-source", "media-xl");
2317        checkMediaSource('media-xl');
2318      }
2319    }
2320  };
2321  
2322  lpc_template.popupAdaptiveBlock = function () {
2323  
2324    let decorPopupWrap = document.querySelector(".lp-popup-inner .decor-wrap");
2325    
2326    if(decorPopupWrap) {
2327    let decorPopupWrapWidth = decorPopupWrap.offsetWidth;
2328      if (decorPopupWrapWidth < 480) {
2329        decorPopupWrap.setAttribute("data-media-source", "media-xs");
2330        checkMediaSource('media-xs');
2331      } else if (decorPopupWrapWidth < 768) {
2332        decorPopupWrap.setAttribute("data-media-source", "media-sm");
2333        checkMediaSource('media-sm');
2334      } else if (decorPopupWrapWidth < 992) {
2335        decorPopupWrap.setAttribute("data-media-source", "media-md");
2336        checkMediaSource('media-md');
2337      } else if (decorPopupWrapWidth < 1280) {
2338        decorPopupWrap.setAttribute("data-media-source", "media-lg");
2339        checkMediaSource('media-lg');
2340      } else if (decorPopupWrapWidth >= 1280) {
2341        decorPopupWrap.setAttribute("data-media-source", "media-xl");
2342        checkMediaSource('media-xl');
2343      }
2344    }
2345  };
2346  
2347  
2348  
2349
2350  lpc_template.checkMapInitialization = function ($blocks) {
2351    $blocks.each(function () {
2352      var $this = $(this),
2353        id = $this.attr("id");
2354
2355      if (initializedMaps.includes(id) && $this.children().length) {
2356        return;
2357      }
2358
2359      var inViewport = isElementInViewport(this);
2360      
2361      if (inViewport) {
2362        initializedMaps.push(id);
2363
2364        lpc_template.initMaps($this);
2365      }
2366    });
2367    
2368  };
2369
2370  lpc_template.initGoogleMaps = function (options) {
2371    var map = new google.maps.Map(document.getElementById(options.id), {
2372      zoom: parseInt(options.zoom),
2373      scrollwheel: false,
2374      center: new google.maps.LatLng(options.center[0], options.center[1]),
2375    });
2376
2377    $.each(options.data, function (key, item) {
2378      var marker = new google.maps.Marker({
2379        position: new google.maps.LatLng(item.coords[0], item.coords[1]),
2380        map: map,
2381        title: item.name,
2382      });
2383
2384      var infowindow = new google.maps.InfoWindow({
2385        content:
2386          '<div class="baloon-content">' +
2387          '<h5 class="lp-header-title-5" style="margin: 0; padding-bottom: 3px; color: inherit;">' +
2388          item.name +
2389          "</h5>" +
2390          item.desc +
2391          "</div>",
2392      });
2393
2394      google.maps.event.addListener(marker, "click", function () {
2395        infowindow.open(map, marker);
2396      });
2397    });
2398  };
2399  
2400  
2401
2402	  //https://pastebin.com/zK79krwA старая версия
2403	lpc_template.initYandexMaps = function (options, objectListFlag) {
2404 
2405		let $wrapper = $('#'+options.id).parents('.lpc-block');
2406	 
2407		if (objectListFlag) {
2408			let groups = options.data;
2409	 
2410			var map = new ymaps.Map(options.id, {
2411		        center: options.center,
2412		        zoom: options.zoom,
2413		        behaviors: ["drag", "rightMouseButtonMagnifier"],
2414		    }, {
2415		        searchControlProvider: 'yandex#search'
2416		    });
2417	 
2418			for (var i = 0; i < groups.length; i++) {
2419				createGroup(groups[i]);
2420			}
2421	 
2422			if (options.data[0].items.length > 1) {
2423	            map.setBounds(map.geoObjects.getBounds());
2424	            map.setZoom(map.getZoom() - 1);
2425	        }
2426	 
2427	 
2428		} else {
2429		    var map = new ymaps.Map(options.id, {
2430		      center: options.center,
2431		      zoom: options.zoom,
2432		      behaviors: ["drag", "rightMouseButtonMagnifier"],
2433		    });
2434	 
2435		};
2436	 
2437	    map.controls.add(new ymaps.control.ZoomControl());
2438	 
2439	    
2440		var MyBalloonContentLayoutClass = ymaps.templateLayoutFactory.createClass(
2441	        options.customballon || 
2442	        '<div class="baloon-content" style="padding: 0 10px;">' +
2443	        '<h5 style="margin: 0;">$[properties.name]</h5>' +
2444	        '<p>$[properties.desc]</p></div>'
2445	    );
2446	
2447	    // 2. Макет кастомной метки (используется только если options.customPin == true)
2448	    var MyIconContentLayout = ymaps.templateLayoutFactory.createClass(
2449	        '<div class="map-label-wrapper">' +
2450	            '<div class="map-label-img" style="background-image: url($[properties.image]);"></div>' +
2451	            '<span class="map-label-name">$[properties.name]</span>' +
2452	        '</div>'
2453	    );
2454		
2455	    if (options.cluster) {
2456			myCollection = new ymaps.Clusterer({
2457				preset: 'islands#clusterIcons', 
2458			    clusterIconColor: options.customcolor || '#ff0000',
2459				groupByCoordinates: false,
2460				clusterDisableClickZoom: false,
2461				clusterHideIconOnBallonOpen: false,
2462				geoObjectHideIconOnBallonOpen: false
2463			});
2464		} else {
2465			myCollection = new ymaps.GeoObjectCollection();
2466		}
2467	 
2468	    $.each(options.data, function (key, item) {
2469			if (options.custompin) {
2470				myCollection.add(
2471					new ymaps.Placemark(item.coords, item, {
2472					iconLayout : 'default#imageWithContent',
2473					iconContentLayout : MyIconContentLayout,
2474					balloonContentLayout: MyBalloonContentLayoutClass,
2475					iconImageHref : 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
2476					iconImageSize : [180, 40],
2477					iconImageOffset : [-20, -20],
2478					iconContentOffset : [0, 0]
2479					})
2480				);
2481			}
2482			else{	
2483				if(this.image){
2484					myCollection.add(
2485						new ymaps.Placemark(item.coords, item, {
2486						balloonContentLayout: MyBalloonContentLayoutClass,
2487						iconLayout: 'default#image',
2488						iconImageHref: this.image,
2489						iconImageOffset: [-15, -15],
2490						})
2491					);
2492				}	else{
2493					myCollection.add(
2494						new ymaps.Placemark(item.coords, item, {
2495						balloonContentLayout: MyBalloonContentLayoutClass,
2496						iconImageOffset: [-15, -15],
2497						preset: this.icon,
2498						iconColor: this.color,
2499						})
2500					);
2501				}
2502			}
2503	    });
2504	 
2505	    map.geoObjects.add(myCollection);
2506	 
2507	    $("#" + options.id).data("ymaps", map);
2508	 
2509		function createGroup(group) {
2510			if(group.image){
2511				var collection = new ymaps.GeoObjectCollection(null, {iconImageHref: group.image, iconImageOffset: [-15, -15], iconLayout: 'default#image', iconColor: group.color});
2512			}else{
2513				var collection = new ymaps.GeoObjectCollection(null, {preset
2513: group.style,  iconColor: group.color});
2514			}
2515			map.geoObjects.add(collection);
2516	 
2517			for (var j = 0; j < group.items.length; j++) {
2518				createItems(group.items[j], collection, j);
2519			}
2520	 
2521		}
2522	 
2523		function createItems(item, collection, index) {
2524			var placemark = new ymaps.Placemark(item.center, { balloonContent: item.name });
2525			collection.add(placemark);
2526	 
2527			$wrapper.find('.lpc-map-click').eq(index).on('click', function (e) {
2528				var $clickedItem = $(this);
2529	 
2530	 
2531				if ($(e.target).closest('a').length && $(this).find('a').length) {
2532			        return;
2533			    }
2534	 
2535	 
2536				$wrapper.find('.lpc-map-click').removeClass('active');
2537	 
2538				$clickedItem.addClass('active');
2539	 
2540				if (!placemark.balloon.isOpen()) {
2541					placemark.balloon.open();
2542				} else {
2543					placemark.balloon.close();
2544				}
2545				map.setCenter(placemark.geometry.getCoordinates(), map.getZoom(), {
2546					duration: 500
2547				});
2548	 
2549				return false;
2550			});
2551		}
2552	};
2553	
2554	
2555	lpc_template.initMaps = function ($block) {
2556
2557		var options = $block.data("init-params");
2558		
2559		if (!options) {
2560			return;
2561		}
2562		
2563		var isObjectList = $block.data("object-list");
2564	
2565		if (typeof options === "string" && options.trim()) {
2566			try {
2567				options = JSON.parse(options.replace(/\n/g, "\\n"));
2568			} catch (e) {
2569				console.error("Ошибка парсинга JSON:", e, options);
2570				options = {};
2571			}
2572		}
2573	
2574		if (typeof options.center === "string") {
2575			options.center = options.center.split(",");
2576		}
2577	
2578		if (options.data && typeof options.data === "object") {
2579			$.each(options.data, function (key, item) {
2580				if (item && typeof item.coords === "string") {
2581					item.coords = item.coords.split(",");
2582				}
2583			});
2584		}
2585	
2586		var keyMap = options.key ?? '';
2587	
2588		if (options.type === "google") {
2589			if (window.google && window.google.maps) {
2590				lpc_template.initGoogleMaps(options);
2591			} else {
2592				var script = document.createElement("script");
2593				script.async = "async";
2594				script.src = `//maps.googleapis.com/maps/api/js?key=${keyMap}`;
2595				document.body.append(script);
2596	
2597				script.onload = function () {
2598					lpc_template.initGoogleMaps(options);
2599				};
2600			}
2601		} else {
2602			if (typeof window.ymaps !== 'undefined') {
2603				lpc_template.initYandexMaps(options, isObjectList);
2604			} else {
2605				var htmlLang = document.documentElement.lang;
2606				var script = document.createElement("script");
2607				script.async = "async";
2608				if (htmlLang == "en") {
2609					if (keyMap != "") {
2610						script.src = `//api-maps.yandex.ru/2.1/?apikey=${keyMap}&lang=en_RU`;
2611					} else {
2612						script.src = `//api-maps.yandex.ru/2.1/?lang=en_RU`;
2613					}
2614				} else {
2615					if (keyMap != "") {
2616						script.src = `//api-maps.yandex.ru/2.1/?apikey=${keyMap}&lang=ru_RU`;
2617					} else {
2618						script.src = `//api-maps.yandex.ru/2.1/?lang=ru_RU`;
2619					}
2620				}
2621	
2622				document.body.append(script);
2623	
2624				script.onload = function () {
2625					ymaps.ready(function () {
2626						lpc_template.initYandexMaps(options, isObjectList);
2627					});
2628				};
2629			}
2630		}
2631	};
2632  
2633  
2634	/*lpc_template.queue.lpcTriggerButton = function ($self) {
2635	    let $block = $self.find('.lpc-constructor');
2636	    let $button = $block.find('.lpc-video-editor__button');
2637	    let $fillingButton = $block.find('.edit-layout');
2638	    
2639	    if (s3LP.is_cms && $block.length && $button.length && $fillingButton.length) {
2640	        $button.on('click', function() {
2641	            $fillingButton.trigger('click');
2642	        });
2643	    }
2644	};*/
2645	
2646	
2647  lpc_template.queue.lpcMapsEditorInit = function ($self) {
2648  		var $block = $self.find(".js-lpc-simple-map");
2649  		
2650	  	if(s3LP.is_cms){
2651	  		if ($block.length) {
2652	  			setTimeout(function() {
2653	  				lpc_template.initMaps($block);
2654	  			}, 200);
2655	  		}
2656	  	}
2657  };
2658  
2659  lpc_template.queue.lpcTriggerPopupBlock = function ($self) {
2660  		var $block = $self.find("[data-popup-type]");
2661  		
2662  		if($block.length){
2663  			document.addEventListener('lpcTriggerPopupInitDone', function(){
2664		    	lpc_template.popupAdaptiveBlock();
2665		    });
2666  		}
2667  };
2668
2669	lpc_template.queue.lpcTimer = function ($self) {
2670		var $block = $self.find(".js-lp-timer"),
2671			htmlLang = document.documentElement.lang,
2672			timerDays,
2673			timerHours,
2674			timerMinutes,
2675			timerSeconds,
2676			formatOut;
2677
2678		if (htmlLang == "de" || htmlLang == "en") {
2679			timerDays = "Days";
2680			timerHours = "Hours";
2681			timerMinutes = "Minutes";
2682			timerSeconds = "Seconds";
2683		} else {
2684			timerDays = "Дней";
2685			timerHours = "Часов";
2686			timerMinutes = "Минут";
2687			timerSeconds = "Секунд";
2688		}
2689
2690		var formatOut =
2691			'<div class="lp-ui-timer__item"><div class="lp-ui-timer__item-number lp-header-title-2" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-number">%d</div><div class="lp-ui-timer__item-text lp-header-text-3" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-text">' +
2692			timerDays +
2693			'</div></div><div class="lp-ui-timer__item"><div class="lp-ui-timer__item-number lp-header-title-2" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-number">%h</div><div class="lp-ui-timer__item-text lp-header-text-3" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-text">' +
2694			timerHours +
2695			'</div></div><div class="lp-ui-timer__item"><div class="lp-ui-timer__item-number lp-header-title-2" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-number">%m</div><div class="lp-ui-timer__item-text lp-header-text-3" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-text">' +
2696			timerMinutes +
2697			'</div></div><div class="lp-ui-timer__item"><div class="lp-ui-timer__item-number lp-header-title-2" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-number">%s</div><div class="lp-ui-timer__item-text lp-header-text-3" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-text">' +
2698			timerSeconds +
2699			"</div></div>";
2700			
2701		var formatEnd =
2702			'<div class="lp-ui-timer__item"><div class="lp-ui-timer__item-number lp-header-title-2" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-number">00</div><div class="lp-ui-timer__item-text lp-header-text-3" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-text">' +
2703			timerDays +
2704			'</div></div><div class="lp-ui-timer__item"><div class="lp-ui-timer__item-number lp-header-title-2" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-number">00</div><div class="lp-ui-timer__item-text lp-header-text-3" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-text">' +
2705			timerHours +
2706			'</div></div><div class="lp-ui-timer__item"><div class="lp-ui-timer__item-number lp-header-title-2" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-number">00</div><div class="lp-ui-timer__item-text lp-header-text-3" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-text">' +
2707			timerMinutes +
2708			'</div></div><div class="lp-ui-timer__item"><div class="lp-ui-timer__item-number lp-header-title-2" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-number">00</div><div class="lp-ui-timer__item-text lp-header-text-3" data-elem-type="text" data-lp-selector=".lp-ui-timer__item-text">' +
2709			timerSeconds +
2710			"</div></div>";
2711
2712	if ($block.length) {
2713		$block.each(function () {
2714			var $this = $(this);
2715			
2716			$this.lpcTimer({
2717				format_in: "%d.%M.%y %h:%m:%s",
2718				language: htmlLang,
2719				update_time: s3LP.is_cms ? 100000 : 1000,
2720				format_out: formatOut,
2721					onEnd: function () {
2722						if ($this.closest('.lpc-banner__timer').length) {
2723							$this.closest('.lpc-banner__timer').hide();
2724						} else {
2725							$this.closest('.lp-ui-timer-wrapper').hide();
2726						}
2727					},
2728				});
2729			});
2730		}
2731  	};
2732
2733  lpc_template.queue.formInputs = function ($self) {
2734    $doc.on("click", ".js-select, .js-multi_select", function () {
2735      var $this = $(this),
2736        openedClass = "_opened",
2737        $thisParent = $this.closest(
2738          ".lp-form-tpl__field-select, .lp-form-tpl__field-multi_select"
2739        ),
2740        $thisList = $thisParent.find(
2741          ".lp-form-tpl__field-select__list, .lp-form-tpl__field-multi_select__list"
2742        );
2743
2744       if(!s3LP.is_cms){
2745	      if ($thisParent.hasClass(openedClass)) {
2746	        $thisParent.removeClass(openedClass);
2747	        //$thisList.slideUp();
2748	        
2749	      } else {
2750	        $thisParent.addClass(openedClass);
2751	        //$thisList.slideDown();
2752	      }
2753      }
2754      
2755      if(s3LP.is_cms){
2756      	
2757      	if ($thisList.hasClass(openedClass)) {
2758	        $thisList.removeClass(openedClass);
2759	      } else {
2760	        $thisList.addClass(openedClass);
2761	      }
2762      }
2763    });
2764    $(document).ready(function () {
2765      $(".js-choose-select._checked").each(function () {
2766        var $this = $(this),
2767          thisText = $this.text(),
2768          $thisParent = $this.closest(".lp-form-tpl__field-select"),
2769          checkedClass = "_checked";
2770
2771        $thisParent.find(".js-choose-select").removeClass(checkedClass);
2772        $thisParent.find(".lp-form-tpl__field-select__input").text(thisText);
2773        $thisParent.parent().find("input").val(thisText);
2774      });
2775    });
2776
2777    $doc.on("click", ".js-choose-select", function () {
2778      var $this = $(this),
2779        thisText = $this.text(),
2780        $thisParent = $this.closest(".lp-form-tpl__field-select"),
2781        checkedClass = "_checked";
2782
2783      if (!$this.hasClass(checkedClass)) {
2784        $thisParent.find(".js-choose-select").removeClass(checkedClass);
2785        $this.addClass(checkedClass);
2786        $thisParent.find(".lp-form-tpl__field-select__input").text(thisText);
2787        $thisParent.parent().find("input").val(thisText);
2788      }
2789
2790      //$thisParent.find(".lp-form-tpl__field-select__list").slideUp();
2791      $thisParent.removeClass("_opened");
2792    });
2793
2794    $doc.on("click", ".js-choose-milti_select", function () {
2795      var $this = $(this),
2796        $thisParent = $this.closest(".lp-form-tpl__field-multi_select"),
2797        checkedClass = "_checked";
2798
2799      if (!$this.hasClass(checkedClass)) {
2800        $this.addClass(checkedClass);
2801      } else {
2802        $this.removeClass(checkedClass);
2803      }
2804
2805      var choosenElements = $thisParent.find("." + checkedClass),
2806        choosenElementsText = [];
2807
2808      choosenElements.each(function () {
2809        choosenElementsText.push($(this).text());
2810      });
2811
2812      $thisParent
2813        .find(".lp-form-tpl__field-multi_select__input--count")
2814        .text(choosenElements.length);
2815      $thisParent.parent().find("input").val(choosenElementsText.join(", "));
2816    });
2817
2818	$doc.on("click", function (e) {
2819		if(!s3LP.is_cms) {
2820			if (!$(e.target).closest('.lp-form-tpl__field-select').length) {
2821				$doc.find(".lp-form-tpl__field-select").removeClass("_opened");
2822				//$doc.find(".lp-form-tpl__field-select__list") .slideUp();
2823			};
2824			
2825			if (!$(e.target).closest('.lp-form-tpl__field-multi_select').length) {
2826				$doc.find(".lp-form-tpl__field-multi_select").removeClass("_opened");
2827				//$doc.find(".lp-form-tpl__field-multi_select__list") .slideUp();
2828			}
2829		}
2830	});
2831  };
2832  
2833  
2834	lpc_template.queue.popupFormHiddenInputFolder = function ($self) {
2835	   
2836	    if ($doc.find('[data-alias="product_name"]').length && $doc.find('.lpc-folder-name[data-folder-name]').length) {
2837	
2838	        $doc.on('click', function (e) {
2839	            const $folderItem = $(e.target).closest('.lpc-folder-name');
2840	
2841	            if ($folderItem.length) {
2842	                const folderName = $folderItem.data('folder-name');
2843	                
2844	                if (folderName) {
2845	                    $('.lp-popup-wrapper form input[data-alias="product_name"]').val(folderName);
2846	                }
2847	            }
2848	        });
2849	    }
2850	};
2851  
2852	lpc_template.queue.productPopupFormHiddenInput = function ($self) {
2853	    let $blocks = $self.find('.lpc-product-9');
2854	
2855	    if ($blocks.length) {
2856	        $self.on("click", ".lpc-popup-hide-input-check", function (e) {
2857	            
2858	            $blocks.each(function () {
2859	                var $productBlock = $(this);
2860	                
2861	                if ($productBlock.find("input[data-alias='product_name']").length && $productBlock.find(".lpc-product-name [data-name-product]").length) {
2862	                	
2863	                    var prodName = $productBlock.find('.lpc-product-name [data-name-product]').data('name-product');
2864	
2865	                    if (prodName) {
2866							setTimeout(function () {
2867	                        	$productBlock.find('form input[data-alias="product_name"]').val(prodName);
2868							}, 100);
2869	                    }
2870	                }
2871	            });
2872	        });
2873	    }
2874	};
2875  
2876
2877  	lpc_template.queue.popupFormHiddenInput = function ($self) {
2878  		if($doc.find("[data-alias='product_name']" && $doc.find("[data-form-hide-input]"))){
2879  			$doc.on("click", function (e) {
2880  				
2881  				if($(e.target).closest('.lpc-popup-hide-input-check').length) {
2882  					var $this = $(this);
2883  					
2884  						
2885  					if($(e.target).closest('.lpc-tarifs-compare').length){
2886  						var prodName = $(e.target).closest('.lpc-popup-hide-input-check').data('button-name');
2887  					}	else {
2888  						var prodName = $(e.target).closest('.lpc-product-name').find('[data-name-product]').data('name-product');
2889  					}
2890  					
2891  					$('.lp-popup-wrapper form input[data-alias=product_name]').val(prodName);
2892  				}
2893  			});
2894  		}
2895  	};
2896  	
2897  	lpc_template.queue.popupFastPayData = function ($self) {
2898  		var searchLinkPopupText = "popup";
2899  		var searchLinkScrollText = "popup";
2900  		
2901  		if(s3LP.is_cms) {
2902  			$(document).ready(function () {
2903  				$(".lpc-popup-fastpay .lpc-popup-fastpay__form-price").text('0');
2904  			});
2905  		}
2906
2907  		
2908  		$doc.on("click", function (e) {
2909  			if($(e.target).closest('.lpc-tarifs-compare').length){
2910  				if($(e.target).closest('.lpc-popup-hide-input-check').length) {
2911  					$(e.target).closest('.lpc-popup-hide-input-check').each(function(){
2912  						var prodPrice = $(this).data('button-index');
2913  						var prodPriceCustom = prodPrice.replace(/\D/g, '');
2914  						
2915  						if (prodPrice.indexOf('/') !== -1) {
2916							var prodPrice = false;
2917						}
2918						
2919  						if(prodPrice) {
2920							$('.lpc-popup-fastpay__form').show();
2921		  					$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').val(prodPriceCustom).hide();
2922		  					$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lp-payment__form').removeClass('_input-active');
2923		  					
2924		  					if($('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lpc-popup-fastpay__content').find('.lpc-popup-fastpay__form-price').length == 0){
2925		  						$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lpc-popup-fastpay__content').find('.lpc-popup-fastpay__form-price').text(prodPrice).show();
2926		  					}else {
2927		  						$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lpc-popup-fastpay__content').find('.lpc-popup-fastpay__form-price').text(prodPrice);
2928		  					}
2929  						}
2930  						else {
2931							$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lp-payment__form').addClass('_input-active');
2932			  				$('.lpc-popup-fastpay__form').hide();
2933			  				$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').val("").show();
2934						}
2935  					});
2936  					
2937			  		var prodName = $(e.target).closest('.lpc-popup-hide-input-check').data('button-name');
2938			  		
2939			  		if ($('.lp-popup-wrapper .lp-payment__form form').find('input[name=_order_details]').length) {
2940				  		$('.lp-popup-wrapper .lp-payment__form form').find('input[name=_order_details]').val(prodName);
2941			  		}
2942	  			}
2943  			} else {
2944	  			if($(e.target).closest('.lpc-popup-hide-input-check').length) {
2945	  				if($doc.find("[name='price']") && $doc.find(".lp-payment__form") && $(e.target).attr('href').includes(searchLinkPopupText) && $(e.target).closest('.lpc-product-name').find('[data-price-product]').length){
2946						var $this = $(this),
2947						prodPrice = $(e.target).closest('.lpc-product-name').find('[data-price-product]').data('price-product');
2948						if (prodPrice.indexOf('/') !== -1) {
2949							var prodPrice = false;
2950						}else{
2951							var prodPriceCustom = $(e.target).closest('.lpc-product-name').find('[data-price-product]').data('price-product').replace(/\D/g, '');
2952						}
2953						
2954						if(prodPrice) {
2955							$('.lpc-popup-fastpay__form').show();
2956		  					$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').val(prodPriceCustom).hide();
2957		  					$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lp-payment__form').removeClass('_input-active');
2958		  					
2959		  					if($('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lpc-popup-fastpay__content').find('.lpc-popup-fastpay__form-price').length == 0){
2960		  						$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lpc-popup-fastpay__content').find('.lpc-popup-fastpay__form-price').text(prodPrice).show();
2961		  					}else {
2962		  						$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lpc-popup-fastpay__content').find('.lpc-popup-fastpay__form-price').text(prodPrice);
2963		  					}
2964						}else {
2965							$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lp-payment__form').addClass('_input-active');
2966			  				$('.lpc-popup-fastpay__form').hide();
2967			  				$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').val("").show();
2968						}
2969	  					
2970	  				} else if($doc.find("[name='price']") && $doc.find(".lp-payment__form") && $(e.target).attr('href').includes(searchLinkPopupText) && !$(e.target).closest('.lpc-product-name').find('[data-price-product]').length) {
2971	  					$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lp-payment__form').addClass('_input-active');
2972	  					$('.lpc-popup-fastpay__form').hide();
2973	  					$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').val("").show();
2974	  					$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').siblings('.lp-form-tpl__field-text-elem').hide();
2975	  				}
2976	  				var prodName = $(e.target).closest('.lpc-product-name').find('[data-name-product]').data('name-product');
2977			  		if ($('.lp-popup-wrapper .lp-payment__form form').find('input[name=_order_details]').length) {
2978				  		$('.lp-popup-wrapper .lp-payment__form form').find('input[name=_order_details]').val(prodName);
2979			  		}
2980	  			}
2981	  			
2982	  			/*if($(e.target).closest('.lpc-popup-hide-input-check').length && (!$(e.target).attr('href').includes(searchLinkPopupText) && !$(e.target).attr('href').includes(searchLinkScrollText)) && $(e.target).closest('.lpc-product-name').find('[data-price-product]').length){
2983	  				var buttonLink = $(e.target).attr('href');
2984	  				prodPrice = $(e.target).closest('.lpc-product-name').find('[data-price-product]').data('price-product');
2985	  				var fastPayLink = buttonLink + '?price=' + prodPrice;
2986	  				e.preventDefault();
2987	  				window.location.href = fastPayLink;
2988	  			}*/
2989  			}
2990  			if ($(e.target).closest('a').length && $(e.target).closest('.lpc-popup-hide-input-check').length == 0) {
2991  				$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').closest('.lp-payment__form').addClass('_input-active');
2992  				$('.lpc-popup-fastpay__form').hide();
2993  				$('.lpc-popup-fastpay .lp-payment-inner form input[name="price"]').val("").show();
2994  			}
2995  		});
2996  	};
2997  	
2998  	lpc_template.queue.fortuneWheel = function ($self) {
2999  		let $block = $self.find('.fortune-wheel'),
3000  			$timeCookies = $block.closest('.lpc-fortuna-1').attr('data-timer-hide'),
3001  			$timeCookies2 = $block.closest('.lpc-popup-fortune').attr('data-timer-hide'),
3002  			$new_minut = $timeCookies,
3003  			$new_minut2 = $timeCookies2;
3004  			
3005  			
3006        function createCookie(name, value, minutes) {
3007	        let expires = "";
3008	        if (minutes) {
3009	            const date = new Date();
3010	            date.setTime(date.getTime() + (minutes * 60 * 1000));
3011	            expires = "; expires=" + date.toUTCString();
3012	        }
3013	        document.cookie = name + "=" + value + expires + "; path=/";
3014	    }
3015        
3016		if ($block.length) {
3017			$block.each(function(){
3018				let $this = $(this);
3019				var parent = $this.closest('.lpc-block');
3020				var parentId = parent.attr('id');
3021
3022				var padding = {
3023				top: 0,
3024				right: 0,
3025				bottom: 0,
3026				left: 0
3027				},
3028				w = 460 - padding.left - padding.right,
3029				h = 460 - padding.top - padding.bottom,
3030				r = Math.min(w, h) / 2,
3031				rotation = 0,
3032				oldrotation = 0,
3033				picked = 100000,
3034				oldpick = [],
3035				rotate = 0,
3036				color = d3.scale.category20(); //category20c()
3037				var form = parent.find('form');
3038				var sendText = parent.find('.question__after-send').data('send-text');
3039				var checkPopupBlock = parent.attr('data-popup-block');
3040				var popupBlockBtn = parent.find('.lpc-popup-fortune__custom-btn');
3041				
3042				if ($timeCookies) {
3043                    $this.closest('.lpc-fortuna-1').find('form').submit(function (e) {
3044                        e.preventDefault();
3045                        createCookie("lpcfortune", "1", parseInt($timeCookies));
3046                        console.log("Cookie создана!");
3047                    });
3048                }
3049				
3050				/*if ($timeCookies) {
3051					$this.closest('.lpc-fortuna-1').find('form').submit(function(){
3052						createCookie("lpcfortune", "1", $new_minut);
3053					});
3054				}*/
3055				if ($timeCookies2) {
3056					$this.closest('.lpc-popup-fortune').find('form').submit(function(){
3057						createCookie("lpcfortune2", "1", $new_minut2);
3058					});
3059				}
3060				
3061				function hexToRgb(hex) {
3062				  // Удаляем возможный символ #
3063				  hex = hex.replace(/^#/, '');
3064				
3065				  // Проверяем наличие корректной длины
3066				  if (hex.length !== 6) {
3067				    throw new Error('Неправильный формат шестнадцатеричного цвета. Ожидается формат "#RRGGBB".');
3068				  }
3069				
3070				  // Разбиваем на составляющие R, G и B
3071				  const r = parseInt(hex.slice(0, 2), 16);
3072				  const g = parseInt(hex.slice(2, 4), 16);
3073				  const b = parseInt(hex.slice(4, 6), 16);
3074				
3075				  return { r, g, b };
3076				}
3077				
3078				function getContrastColor(rgbStr) {
3079				  let customBg = hexToRgb(rgbStr);
3080				  let textColor = Math.round((customBg.r * 299 + customBg.g * 587 + customBg.b * 114) / 1000);
3081				  return (textColor > 150) ? '#000' : '#fff';
3082				}
3083			
3084				var data = $this.data("labels");
3085				data = data.replace(/,$/, '');
3086				data = data.replace(/"/g, '\\"');
3087				data = data.replace(/'/g, '"');
3088				data = JSON.parse('[' + data + ']');
3089				
3090				var infiniteRotate = $this.data("infinite")
3091				
3092				var svg = d3.select('#'+parentId + ' .fortune-wheel')
3093					.append("svg")
3094					.data([data])
3095					.attr("width", w + padding.left + padding.right)
3096					.attr("height", h + padding.top + padding.bottom);
3097				
3098				var container = svg.append("g")
3099					.attr("class", "chartholder")
3100					.attr("transform", "translate(" + (w / 2 + padding.left) + "," + (h / 2 + padding.top) + ")");
3101					
3102				container.append("circle")
3103					.attr("cx", 0)
3104					.attr("cy", 0)
3105					.attr("r", 230)
3106					.style({
3107						"fill": "var(--primary-color-base)"
3108					});
3109				
3110				var vis = container
3111					.append("g");
3112					
3113				if(infiniteRotate) {
3114					vis.attr("class", "infinite-rotate");
3115				} else {
3116					if(data.length % 2 === 0 && data.length / 2 % 2 !== 0) {
3117						rotate = 360 / data.length / 2;
3118						vis.style({
3119							"transform": "rotate(" + rotate + "deg)"
3120						});
3121						oldrotation = rotate
3122					} 	
3123				}
3124				
3125				var pie = d3.layout.pie().sort(null).value(function(d) {
3126					return 1;
3127				});
3128				
3129				// declare an arc generator function
3130				var arc = d3.svg.arc().outerRadius(r);
3131				
3132				// select paths, use arc generator to draw
3133				var arcs = vis.selectAll("g.slice")
3134					.data(pie)
3135					.enter()
3136					.append("g")
3137					.attr("class", "slice");
3138				
3139				
3140				arcs.append("path")
3141					.attr("fill", function(d, i) {
3142						return i % 2 ? 'var(--primary-color-base)' : 'var(--primary-color-l-5)';
3143					})
3144					.attr("d", function(d) {
3145						return arc(d);
3146					});
3147				
3148				// add the text
3149				arcs.append("text")
3150					.attr("text-anchor", "middle")
3151					.attr("class", "lp-header-text-3")
3152					.style({
3153						"fill": function() {
3154							// Получаем fill у path, к которому относится текущий текстовый элемент
3155							let pathFill = d3.select(this.parentNode).select("path").attr("fill");
3156							let pathFillColor = getComputedStyle(document.documentElement).getPropertyValue(pathFill.match(/var\((.*?)\)/)?.[1])
3157							return getContrastColor(pathFillColor);
3158						  }
3159					})
3160					.text(function(d, i) {
3161						return data[i].label;
3162				});
3163
3164
3165				function beforeSubmitActions(event) {
3166					event.preventDefault();
3167					container.call(spin);
3168				}
3169				
3170				
3171				function firstStepSpin(event) {
3172					event.preventDefault();
3173					popupBlockBtn.addClass('lpc_pointer_events_none');
3174					container.call(popupspin);
3175					
3176					setTimeout(function() {
3177						parent.find('.lpc-popup-fortune__step-1').hide();
3178						parent.find('.lpc-popup-fortune__step-2').show();
3179					}, 3000);
3180					
3181				}
3182				
3183				if(checkPopupBlock) {
3184					popupBlockBtn.on('click', firstStepSpin);
3185					
3186					form.on('submit', popupSubmit);
3187					
3188					$('.lpc-popup-fortune__finish-btn').on('click', function(){
3189						$(this).closest('.lp-popup-wrapper').find('.js-close-popup').trigger('click');	
3190					});
3191				}else {
3192					form.on('submit', beforeSubmitActions);
3193				}
3194				
3195				
3196				wrap(arcs.selectAll("text"), 140);
3197				
3198				function wrap(text, width) {
3199				
3200					text.each(function() {
3201						var text = d3.select(this),
3202							words = text.text().split(/\s+/).reverse(),
3203							word,
3204							line = [],
3205							lineNumber = 0,
3206							lineHeight = 1, // ems
3207							y = text.attr("y"),
3208							dy = 0,
3209							tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
3210						while (word = words.pop()) {
3211							line.push(word);
3212							tspan.text(line.join(" "));
3213							if (tspan.node().getComputedTextLength() > width) {
3214								line.pop();
3215								tspan.text(line.join(" "));
3216								line = [word];
3217								tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", Math.sqrt(++lineNumber) * lineHeight + dy + "em").text(word);
3218							}
3219							text.attr("transform", function(d) {
3220								d.innerRadius = 0;
3221								d.outerRadius = r;
3222								d.angle = (d.startAngle + d.endAngle) / 2;
3223								return "rotate(" + (d.angle * 180 / Math.PI - 90 + 1.75 - lineNumber * 2) + ")translate(" + (d.outerRadius - 90) + ")";
3224							})
3225						}
3226					});
3227				}
3228				
3229				
3230				function spin(d) {
3231				
3232					container.on("click", null);
3233				
3234					//all slices have been seen, all done
3235					//console.log("OldPick: " + oldpick.length, "Data length: " + data.length);
3236					if (oldpick.length == data.length) {
3237						container.on("click", null);
3238						return;
3239					}
3240				
3241					var ps = 360 / data.length,
3242						pieslice = Math.round(1440 / data.length),
3243						
3244						rng = Math.floor((Math.random() * 1440) + 360);
3245						
3246					rotation = (Math.round(rng / ps) * ps);
3247				
3248					picked = Math.round(data.length - (rotation % 360) / ps);
3249					picked = picked >= data.length ? (picked % data.length) : picked;
3250				
3251				
3252					if (oldpick.indexOf(picked) !== -1) {
3253						d3.select(this).call(spin);
3254						return;
3255					} else {
3256						oldpick.push(picked);
3257					}
3258				
3259					rotation += 90 - Math.round(ps / 2) - rotate;
3260					
3261					if(infiniteRotate) {
3262						setTimeout(function () {
3263							vis.attr("class", "stop-rotate");
3264						}, 2600);
3265					}
3266					
3267					
3268					vis.transition()
3269						.style({
3270							"animation-duration": "2.9s"
3271						})
3272						.duration(3000)
3273						.attrTween("style", rotTween)
3274						.each("end", function() {
3275							
3276							//mark question as seen
3277		                    d3.select('#' + parentId + ' .slice:nth-child(' + (picked + 1) + ') path')
3278		                        .attr("fill", "var(--primary-color-d-10)");
3279		                        
3280	                        d3.select('#' + parentId + ' .slice:nth-child(' + (picked + 1) + ') text').style({
3281								"fill": function() {
3282									// Получаем fill у path, к которому относится текущий текстовый элемент
3283									let pathFillColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color-d-10')
3284									return getContrastColor(pathFillColor);
3285								  }
3286							})
3287				
3288							//populate question
3289							$('#'+parentId).find('[data-alias="prize"]').val(data[picked].label);
3290							
3291							$('#'+parentId + ' .lp-form-tpl__button').click();
3292							
3293							d3.select('#'+parentId + ' .question__after-send h2')
3294		                        .text(sendText + ' ' + data[picked].label);
3295		                        
3296							$('#'+parentId + ' .question__before-send').hide();
3297							$('#'+parentId + ' .question__after-send').show("slow").fadeOut;
3298							$('#'+parentId + ' .question-message').hide();
3299
3300		                        
3301							$('#'+parentId + ' form').hide();
3302							
3303							createCookie("lpcfortunetext", sendText + ' ' + data[picked].label, $new_minut);
3304							//container.on("click", spin);
3305						});
3306					
3307				}
3308				
3309				function popupSubmit(d) {
3310					$('#'+parentId + ' .lp-form-tpl__button').click();
3311							
3312					/*d3.select('#'+parentId + ' .question__after-send h2')
3313                    .text(sendText + ' ' + data[picked].label);*/
3314                        
3315					$('#'+parentId + ' .question__before-send').hide();
3316					$('#'+parentId + ' .question__after-send').hide()
3317					$('#'+parentId + ' .question-message').hide();
3318					$('#'+parentId + ' form').hide();
3319					
3320					setTimeout(function() {
3321						$('#'+parentId + ' .lpc-popup-fortune__step-2').addClass('_last-step');
3322						$('#'+parentId + ' .lpc-popup-fortune__finish-btn').show();
3323					}, 950);
3324					
3325				}
3326				
3327				function popupspin(d) {
3328				
3329					container.on("click", null);
3330				
3331					//all slices have been seen, all done
3332					if (oldpick.length == data.length) {
3333						container.on("click", null);
3334						return;
3335					}
3336				
3337					var ps = 360 / data.length,
3338						pieslice = Math.round(1440 / data.length),
3339						
3340						rng = Math.floor((Math.random() * 1440) + 360);
3341						
3342					rotation = (Math.round(rng / ps) * ps);
3343				
3344					picked = Math.round(data.length - (rotation % 360) / ps);
3345					picked = picked >= data.length ? (picked % data.length) : picked;
3346				
3347				
3348					if (oldpick.indexOf(picked) !== -1) {
3349						d3.select(this).call(spin);
3350						return;
3351					} else {
3352						oldpick.push(picked);
3353					}
3354				
3355					rotation += 90 - Math.round(ps / 2) - rotate;
3356					
3357					if(infiniteRotate) {
3358						setTimeout(function () {
3359							vis.attr("class", "stop-rotate");
3360						}, 2600);
3361					}
3362					
3363					
3364					vis.transition()
3365						.style({
3366							"animation-duration": "2.9s"
3367						})
3368						.duration(3000)
3369						.attrTween("style", rotTween)
3370						.each("end", function() {
3371							
3372							//mark question as seen
3373		                    d3.select('#' + parentId + ' .slice:nth-child(' + (picked + 1) + ') path')
3374		                        .attr("fill", "var(--primary-color-d-10)");
3375		                        
3376	                        d3.select('#' + parentId + ' .slice:nth-child(' + (picked + 1) + ') text').style({
3377								"fill": function() {
3378									// Получаем fill у path, к которому относится текущий текстовый элемент
3379									let pathFillColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color-d-10')
3380									return getContrastColor(pathFillColor);
3381								  }
3382							})
3383				
3384							//populate question
3385							$('#'+parentId).find('[data-alias="prize"]').val(data[picked].label);
3386							
3387							/*if(!checkPopupBlock) {
3388							$('#'+parentId + ' .lp-form-tpl__button').click();
3389							
3390							d3.select('#'+parentId + ' .question__after-send h2')
3391                    		.text(sendText + ' ' + data[picked].label);
3392		                        
3393							$('#'+parentId + ' .question__before-send').hide();
3394							$('#'+parentId + ' .question__after-send').show();
3395							$('#'+parentId + ' .question-message').hide();
3396
3397		                        
3398							$('#'+parentId + ' form').hide();
3399							}*/
3400							
3401							d3.select('#'+parentId + ' .question__after-send h2')
3402                			.text(sendText + ' ' + data[picked].label);
3403							
3404							$('#'+parentId + ' .question__after-send').show();
3405							$('#'+parentId + ' .lpc-popup-fortune__step-2').show();
3406							
3407							createCookie("lpcfortune2text", sendText + ' ' + data[picked].label, $new_minut2);
3408							
3409							//container.on("click", spin);
3410						});
3411					
3412				}
3413				
3414				//make arrow
3415				svg.append("g")
3416					.attr("transform", "translate(" + (w - 42) + "," + ((h / 2) - 25) + ")")
3417					.append("path")
3418					.attr("class", "wheel-indicator")
3419					.attr("d", "M40.0261 10.6195L11.9636 23.1737C10.386 23.8795 10.386 26.1192 11.9637 26.825L40.0261 39.3793C41.3491 39.9712 42.8428 39.003 42.8428 37.5536V12.4451C42.8428 10.9957 41.3491 10.0276 40.0261 10.6195Z")
3420					.style({
3421						"fill": "white"
3422					});
3423				
3424				//draw spin circle
3425				container.append("circle")
3426					.attr("cx", 0)
3427					.attr("cy", 0)
3428					.attr("r", 20)
3429					.attr("stroke", "#fff")
3430					.attr("stroke-width", "7")
3431					.attr("class", "inner-circle")
3432					.style({
3433						"fill": "var(--primary-color-base)"
3434					});
3435
3436				container.append("circle")
3437					.attr("cx", 0)
3438					.attr("cy", 0)
3439					.attr("r", 230)
3440					.attr("stroke", "#fff")
3441					.attr("class", "outer-circle")
3442					.attr("stroke-width", "10")
3443					.style({
3444						"fill": "transparent"
3445					});
3446					
3447				function rotTween(to) {
3448					var i = d3.interpolate(oldrotation % 360, rotation + rotate);
3449					return function(t) {
3450						return "transform: rotate(" + i(t) + "deg)";
3451					};
3452				}
3453			});
3454		}
3455  	};
3456
3457	lpc_template.queue.calendar = function ($self) {
3458		$doc.on("click", ".lpc-js-form-calendar", function () {
3459			var $this = $(this),
3460				thisCalendarInited = $this.data("calendarInited");
3461				
3462			var clickPosY = event.clientY || event.pageY;
3463		    var windowHeight = $(window).height();
3464		    var clickPosition = (windowHeight - clickPosY);	
3465				
3466			//if (!thisCalendarInited) {
3467			if (clickPosition < 263) {
3468				var bb = $this
3469					.datepickerlpc({
3470						position: 'top left'
3471					})
3472					.data("datepickerlpc");
3473				bb.show();
3474				thisCalendarInited = $this.data("calendarInited", true);
3475			}else {
3476				var bb = $this
3477					.datepickerlpc({
3478						position: 'bottom left'
3479					})
3480					.data("datepickerlpc");
3481				bb.show();
3482				thisCalendarInited = $this.data("calendarInited", true);
3483			}
3484		});
3485	
3486		$doc.on("click", ".lpc-js-form-calendar-interval", function () {
3487			var $this = $(this),
3488				thisCalendarInited = $this.data("calendarInited");
3489				
3490			var clickPosY = event.clientY || event.pageY;
3491		    var windowHeight = $(window).height();
3492		    var clickPosition = (windowHeight - clickPosY);		
3493	
3494			//if (!thisCalendarInited) {
3495			if (clickPosition < 263) {	
3496				var bb = $this
3497					.datepickerlpc({
3498						position: 'top left',
3499						range: true,
3500						multipleDatesSeparator: " - ",
3501					})
3502					.data("datepickerlpc");
3503				bb.show();
3504				thisCalendarInited = $this.data("calendarInited", true);
3505			}else {
3506				var bb = $this
3507					.datepickerlpc({
3508						position: 'bottom left',
3509						range: true,
3510						multipleDatesSeparator: " - ",
3511					})
3512					.data("datepickerlpc");
3513				bb.show();
3514				thisCalendarInited = $this.data("calendarInited", true);
3515			}
3516		});
3517	};
3518	
3519	lpc_template.queue.anchorMenu = function ($self) {
3520		let $block = $self.find('.lpc_anchor_menu_init');
3521		
3522		if (!$block.length) return;
3523	
3524		let links = $block.find('.lpc-anchor-menu-fixed__link');
3525		let booleanValue = $block.data('lpc-choice-elem') === true;
3526	
3527		let fixedBlock = $block.find('.lpc-anchor-menu-fixed');
3528		let mosaicWrap = $(document).find('.mosaic-wrap');
3529		let button = $block.find('.lpc-anchor-menu-fixed__button');
3530		let $lpcWrap = $(document).find('.decor-wrap');
3531	
3532		let hiddenBlockIds = [];
3533	
3534		$lpcWrap.each(function () {
3535			let $this = $(this);
3536	
3537			if (s3LP.is_cms) {
3538				$this.find('.popup-row-block').each(function () {
3539					let popupId = $(this).find('[data-blocks-popup]').data('blocks-popup');
3540					if (popupId !== undefined) hiddenBlockIds.push(popupId);
3541				});
3542			} else {
3543				let popupId = $this.find('[data-blocks-popup]').data('blocks-popup');
3544				let hideId = $this.find('._hide-block').data('block-id');
3545				hiddenBlockIds.push(popupId !== undefined ? popupId : hideId);
3546			}
3547		});
3548	
3549		/* ---------------- MOBILE ---------------- */
3550		
3551		/*if (isMobile) {
3552		    $(document)
3553		        .off('click.anchorMenu')
3554		        .on('click.anchorMenu', '.lpc-anchor-menu-fixed__button', function (e) {
3555		            e.preventDefault();
3556		            e.stopPropagation();
3557		
3558		            $(this)
3559		                .closest('.lpc-anchor-menu-fixed')
3560		                .toggleClass('active');
3561		        });
3562		
3563		    $(document).on('keydown.anchorMenu', function (e) {
3564		        if (e.keyCode === 27) {
3565		            $('.lpc-anchor-menu-fixed').removeClass('active');
3566		        }
3567		    });
3568		
3569		    $(document).on('click.anchorMenuClose', function (e) {
3570		        if (!$(e.target).closest('.lpc-anchor-menu-fixed').length) {
3571		            $('.lpc-anchor-menu-fixed').removeClass('active');
3572		        }
3573		    });
3574		}*/
3575		
3576		if (isMobile) {
3577			$(document).off('click.anchorMenu').on('click.anchorMenu','.lpc-anchor-menu-fixed__button', function (event) {
3578					event.preventDefault();
3579					event.stopPropagation();
3580					$(this).closest('.lpc-anchor-menu-fixed').toggleClass('active');
3581				}
3582			);
3583		
3584			$(document).off('keydown.anchorMenu').on('keydown.anchorMenu', function (event) {
3585				if (event.key === 'Escape') {
3586					$('.lpc-anchor-menu-fixed').removeClass('active');
3587				}
3588			});
3589		
3590			$(document).off('click.anchorMenuClose').on('click.anchorMenuClose', function (event) {
3591				if (!$(event.target).closest('.lpc-anchor-menu-fixed').length) {
3592					$('.lpc-anchor-menu-fixed').removeClass('active');
3593				}
3594			});
3595		}
3596	
3597		/* ---------------- POSITION ---------------- */
3598	
3599		setTimeout(function () {
3600			let buttonHeight = $block.find('.lpc-anchor-menu-fixed__button').outerHeight();
3601			let listHeight = $block.find('.lpc-anchor-menu-fixed__list').outerHeight();
3602			let listBlock = $block.find('.lpc-anchor-menu-fixed__list');
3603	
3604			let $wrapBlock = $block.closest('.lpc-anchor-menu');
3605			let blockId = $wrapBlock.attr('id');
3606			let blockLayout = $wrapBlock.attr('data-block-layout');
3607	
3608			listBlock.toggleClass('no-border-radius', buttonHeight === listHeight);
3609	
3610			if (mosaicWrap.length && !$block.hasClass('lpc_constructor')) {
3611				mosaicWrap.prepend(fixedBlock);
3612				fixedBlock.attr({
3613					id: blockId,
3614					'data-block-layout': blockLayout
3615				});
3616			}
3617		}, 350);
3618	
3619		/* ---------------- LINKS ---------------- */
3620	
3621		links.each(function () {
3622			let $this = $(this);
3623			let blockId = $this.attr('href').replace('#', '');
3624			let offsetValue = parseFloat($this.data('lpc-offset')) || 0;
3625			let offsetValueMobile = parseFloat($this.data('lpc-offset-mobile')) || 0;
3626	
3627			let targetBlock = $('#' + blockId);
3628			let headerElements = targetBlock.find(
3629				'[data-elem-type="header"]:not(.lpc-list-illustration__title--hidden)'
3630			);
3631	
3632			let blockPopupId = parseInt(blockId.replace(/\D/g, ''), 10);
3633			
3634			if (hiddenBlockIds.includes(blockPopupId)) {
3635				$this.parent('.lpc-anchor-menu-fixed__item').remove();
3636				return;
3637			}
3638			
3639			if (headerElements.length && $this.hasClass('lpc-has-block-name')) {
3640				$this.text(headerElements.first().text());
3641			}
3642			
3643			if (!booleanValue && headerElements.length === 0) {
3644				$this.parent('.lpc-anchor-menu-fixed__item').remove();
3645				
3646			}
3647			
3648			$this.off('click.anchorMenuLink').on('click.anchorMenuLink', function (event) {
3649				event.preventDefault();
3650		
3651				if (!targetBlock.length || !targetBlock[0]) return;
3652		
3653				links.removeClass('active');
3654				$this.addClass('active');
3655		
3656				if (isMobile) {
3657					fixedBlock.removeClass('active');
3658				}
3659		
3660				const duration = 800;
3661				const startPosition = window.pageYOffset;
3662				const startTime = performance.now();
3663		
3664				const getTargetPosition = function () {
3665					const offset = isMobile
3666						? offsetValueMobile
3667						: offsetValue;
3668		
3669					const rect = targetBlock[0].getBoundingClientRect();
3670		
3671					return Math.max(
3672						0,
3673						rect.top + window.pageYOffset - offset
3674					);
3675				};
3676		
3677				const easeInOutCubic = function (progress) {
3678					return progress < 0.5
3679						? 4 * progress * progress * progress
3680						: 1 - Math.pow(-2 * progress + 2, 3) / 2;
3681				};
3682		
3683				const animateScroll = function (currentTime) {
3684					const elapsed = currentTime - startTime;
3685					const progress = Math.min(elapsed / duration, 1);
3686					const easedProgress = easeInOutCubic(progress);
3687		
3688					/*
3689					 * Позиция пересчитывается на каждом кадре.
3690					 * Поэтому изменение высоты страницы не вызывает скачок.
3691					 */
3692					const currentTargetPosition = getTargetPosition();
3693		
3694					const scrollPosition =
3695						startPosition +
3696						(currentTargetPosition - startPosition) *
3697						easedProgress;
3698		
3699					window.scrollTo({
3700						top: scrollPosition,
3701						behavior: 'auto'
3702					});
3703		
3704					if (progress < 1) {
3705						requestAnimationFrame(animateScroll);
3706						return;
3707					}
3708		
3709					history.replaceState(
3710						null,
3711						'',
3712						'#' + blockId
3713					);
3714				};
3715		
3716				requestAnimationFrame(animateScroll);
3717			});
3718			
3719			/*$this.on('click', function (event) {
3720				event.preventDefault();
3721	
3722				links.removeClass('active');
3723				$this.addClass('active');
3724	
3725				if (!targetBlock.length) return;
3726	
3727				let offset = isMobile
3728					? targetBlock.offset().top - offsetValueMobile
3729					: targetBlock.offset().top - offsetValue;
3730	
3731				$('html, body').stop().animate(
3732					{ scrollTop: offset },
3733					800,
3734					function () {
3735						history.pushState(null, null, '#' + blockId);
3736					}
3737				);
3738			});*/
3739	
3740			links.removeClass('lpc-opacity');
3741		});
3742	};
3743	
3744	lpc_template.queue.fixedSocialsBox = function ($self) {
3745
3746		const $block = $self.find('.fixed-socials-init');
3747		if (!$block.length) return;
3748			
3749		$block.each(function () {
3750			let $box = $(this);
3751			let $fixedBlock = $box.find('.lpc-fixed-socials-box');
3752			let $container = $box.find('.lpc-fixed-socials-box__container');
3753			let $button = $box.find('.lpc-fixed-socials-box__button');
3754			let $mosaicWrap = $(document).find('.mosaic-wrap');
3755			let offsetDesktop = $fixedBlock.data('lpc-offset');
3756			let offsetMobile = $fixedBlock.data('lpc-offset-mobile');
3757	
3758			if (isMobile) {
3759				$fixedBlock.css('margin-top', offsetMobile + 'px');
3760			} else {
3761				$fixedBlock.css('margin-top', offsetDesktop + 'px');
3762			}
3763			
3764			setTimeout(function () {
3765				if ($mosaicWrap.length && !$box.hasClass('lpc_constructor')) {
3766					$mosaicWrap.prepend($fixedBlock);
3767				}
3768			}, 350);
3769			
3770			$button.on('click', function (e) {
3771				e.stopPropagation();
3772	
3773				const isOpen = $container.hasClass('is-open');
3774				
3775				$('.lpc-fixed-socials-box__container.is-open').not($container).removeClass('is-open');
3776				
3777				if (!isOpen) {
3778					$container.addClass('is-open');
3779				} else {
3780					$container.removeClass('is-open');
3781				}
3782			});
3783			
3784			$(document).on('click.fixedSocials', function (e) {
3785				if (!$(e.target).closest($container).length) {
3786					$container.removeClass('is-open');
3787				}
3788			});
3789		});
3790	};
3791	
3792	lpc_template.queue.movingPictures = function ($self) {
3793	    let $block = $self.find('.lpc_moving_pictures_init');
3794	
3795	    if ($block.length) {
3796	    	
3797	        setTimeout(function () {
3798	        	
3799	            $block.each(function () {
3800	                let $this = $(this),
3801	                    $wrapper = $this.find('.lpc_moving_pictures_wrap'),
3802	                    $marquee = $this.find('.lpc_moving_pictures_move'),
3803	                    marqueeSpeed = $this.data('marquee-speed') || 1,
3804	                	speed = marqueeSpeed,
3805	                    position = 0,
3806	                    animationFrame,
3807	                    wrapperWidth = $wrapper[0].offsetWidth,
3808	                    direction = 'left',
3809	                    isInMiddle = false,
3810	                    totalWidth = 0;
3811	
3812	                if (!s3LP.is_cms) {
3813	                	
3814	                    $marquee.find('.lpc_moving_pictures_item').each(function () {
3815	                        totalWidth += $(this).outerWidth(true);
3816	                    });
3817	
3818	                    while (totalWidth < wrapperWidth) {
3819	                        $marquee.find('.lpc_moving_pictures_item').each(function () {
3820	                            let $clone = $(this).clone();
3821	                            $marquee.append($clone);
3822	                            totalWidth += $clone.outerWidth(true);
3823	                        });
3824	                    }
3825	
3826	                    let clonedContent = $marquee.html();
3827	                    $marquee.html(clonedContent + clonedContent);
3828	                    
3829	                } else {
3830	                	
3831	                	function s3lazyLoadImages() {
3832	                		
3833		                	const $s3lazyImage = $(".lpc-ticker__carousel-mask-item img[data-src]");
3834							
3835		                    const s3LoadImage = (image) => {
3836		                        const src = $(image).attr('data-src');
3837								
3838		                        if (src) {
3839		                            $(image).attr('src', src);
3840		                            $(image).removeAttr('data-src');
3841		                        }
3842		                    };
3843		                    
3844		                    $s3lazyImage.each(function () {
3845		                        s3LoadImage(this);
3846		                    });
3847		                }
3848		                
3849		                s3lazyLoadImages();
3850	                }
3851	
3852	                let marqueeWidth = totalWidth;
3853	                
3854	                function lazyLoadImages() {
3855						const $lazyImage = $(".lpc-ticker__carousel-mask-item img[data-src]");
3856						
3857	                    const loadImage = (image) => {
3858	                        const src = $(image).attr('data-src');
3859							
3860	                        if (src) {
3861	                            $(image).attr('src', src);
3862	                            $(image).removeAttr('data-src');
3863	                        }
3864	                    };
3865	                    
3866	                    const isImageVisible = (image) => {
3867	                        let imgLeft = $(image).offset().left,
3868	                            imgRight = imgLeft + $(image).outerWidth(),
3869	                            wrapperLeft = $wrapper.offset().left,
3870	                            wrapperRight = wrapperLeft + $wrapper.outerWidth();
3871	
3872	                        return imgRight > wrapperLeft && imgLeft < wrapperRight;
3873	                    };
3874	                    
3875	                    $lazyImage.each(function () {
3876	                        if (isImageVisible(this)) {
3877	                            loadImage(this);
3878	                        }
3879	                    });
3880	                }
3881	
3882	                function move() {
3883	                    window.cancelAnimationFrame(animationFrame);
3884	
3885	                    if (direction === 'left') {
3886	                        position -= speed;
3887	                    } else {
3888	                        position += speed;
3889	                    }
3890	
3891	                    if (!s3LP.is_cms) {
3892	                    	
3893	                        if (direction === 'left' && position <= -marqueeWidth) {
3894	                            position = 0;
3895	                        } else if (direction === 'right' && position >= 0) {
3896	                            position = -marqueeWidth;
3897	                        }
3898	
3899	                        $marquee.css('transform', 'translate3d(' + position + 'px, 0, 0)');
3900	
3901	                        animationFrame = window.requestAnimationFrame(move);
3902	                        
3903	                        lazyLoadImages();
3904	
3905	                    } else {
3906	                    	
3907	                        if (direction === 'left' && position <= -(marqueeWidth - wrapperW
3907idth)) {
3908	                            window.cancelAnimationFrame(animationFrame);
3909	                            return;
3910	                        } else if (direction === 'right' && position >= 0) {
3911	                            window.cancelAnimationFrame(animationFrame);
3912	                            return;
3913	                        }
3914	
3915	                        $marquee.css('transform', 'translate3d(' + position + 'px, 0, 0)');
3916	
3917	                        animationFrame = window.requestAnimationFrame(move);
3918	                    }
3919	                }
3920	
3921	                move();
3922	
3923	                var leftRightZoneWidth = wrapperWidth * 0.4;
3924	                var middleZoneWidth = wrapperWidth * 0.2;
3925	
3926	                var getZone = function (posX) {
3927	                    if (posX < leftRightZoneWidth) {
3928	                        return 'left';
3929	                    } else if (posX > wrapperWidth - leftRightZoneWidth) {
3930	                        return 'right';
3931	                    } else {
3932	                        return 'middle';
3933	                    }
3934	                };
3935	
3936	                var prevMouseX;
3937	                var minSpeed = speed;
3938	
3939	                var handleMove = function (event, isTouch = false) {
3940	                    var posX = isTouch ? event.originalEvent.touches[0].pageX - $wrapper[0].getBoundingClientRect().left : event.pageX - $wrapper[0].getBoundingClientRect().left;
3941	                    var zone = getZone(posX);
3942	                    var speedIncrement = 0.03;
3943	                    var maxSpeed = speed + (speed * 0.5);
3944	
3945	                    if (zone === 'left') {
3946	                        direction = 'right';
3947	
3948	                        if (prevMouseX !== undefined) {
3949	                            var distanceMoved = prevMouseX - posX;
3950	                            speed += distanceMoved * speedIncrement;
3951	                            speed = Math.max(minSpeed, Math.min(speed, maxSpeed));
3952	                        }
3953	
3954	                        prevMouseX = posX;
3955	
3956	                    } else if (zone === 'right') {
3957	                        direction = 'left';
3958	
3959	                        if (prevMouseX !== undefined) {
3960	                            var distanceMoved = posX - prevMouseX;
3961	                            speed += distanceMoved * speedIncrement;
3962	                            speed = Math.max(minSpeed, Math.min(speed, maxSpeed));
3963	                        }
3964	
3965	                        prevMouseX = posX;
3966	
3967	                    } else if (zone === 'middle') {
3968	                        window.cancelAnimationFrame(animationFrame);
3969	                        isInMiddle = true;
3970	                        prevMouseX = posX;
3971	                        return;
3972	                    }
3973	
3974	                    if (isInMiddle) {
3975	                        isInMiddle = false;
3976	                        move();
3977	                    }
3978	                };
3979	
3980	                if (isMobile) {
3981	                    $wrapper.on('touchmove', function (event) {
3982	                        handleMove(event, true);
3983	                    });
3984	
3985	                    $wrapper.on('touchend', function () {
3986	                        speed = minSpeed;
3987	                        prevMouseX = undefined;
3988	                        move();
3989	                    });
3990	                } else {
3991	                    $wrapper.on('mousemove', handleMove);
3992	
3993	                    $wrapper.on('mouseleave', function () {
3994	                        speed = minSpeed;
3995	                        prevMouseX = undefined;
3996	                        move();
3997	                    });
3998	                }
3999	            });
4000	            
4001	            lpc_template.queue.lgNew($block);
4002	
4003	        }, 500);
4004	    }
4005	};
4006	
4007	lpc_template.queue.QRcode = function ($self) {
4008		let $block = $self.find('.lpc_qr_init');
4009	
4010		if ($block.length) {
4011			$block.each(function () {
4012				let item = $(this);
4013				let messengerWrap = item.find('.lpc_qr_code_item');
4014			
4015				messengerWrap.each(function () {
4016					let item = $(this);
4017					let containerQr = item.find('.lpc_qr_code_container');
4018					let containerQrPhone = item.find('.lpc_qr_code_container_phone');
4019			
4020					let messengerLinks = item.find('.lpc_qr_code_link');
4021					let messengerLinksPhone = item.find('.lpc_qr_code_link_phone');
4022			
4023					let urls = messengerLinks.map(function () {
4024						return $(this).attr('href');
4025					}).get();
4026			
4027					let urlsPhone = messengerLinksPhone.map(function () {
4028						return $(this).attr('href').replace(/[^\d+]/g, '');
4029					}).get();
4030			
4031					let sizes = messengerLinks.map(function () {
4032						return $(this).attr('data-qr-code-size');
4033					}).get();
4034			
4035					let sizesPhone = messengerLinksPhone.map(function () {
4036						return $(this).attr('data-qr-code-size');
4037					}).get();
4038			
4039					urls.forEach(function (url, index) {
4040						if (containerQr.length) {
4041							createQR(containerQr.eq(index), sizes[index], url);
4042							$('body').append(containerQr.eq(index));
4043						}
4044					});
4045			
4046					urlsPhone.forEach(function (url, index) {
4047						if (containerQrPhone.length) {
4048							createQR(containerQrPhone.eq(index), sizesPhone[index], url);
4049							$('body').append(containerQrPhone.eq(index));
4050						}
4051					});
4052			
4053					messengerLinks.hover(function () {
4054						let index = messengerLinks.index(this);
4055						showQR(containerQr.eq(index), $(this));
4056					}, function () {
4057						let index = messengerLinks.index(this);
4058						hideQR(containerQr.eq(index));
4059					});
4060			
4061					messengerLinksPhone.hover(function () {
4062						let index = messengerLinksPhone.index(this);
4063						showQR(containerQrPhone.eq(index), $(this));
4064					}, function () {
4065						let index = messengerLinksPhone.index(this);
4066						hideQR(containerQrPhone.eq(index));
4067					});
4068			
4069					let activeQR = null;
4070			
4071					function createQR(container, size, url) {
4072						container.qrcode({
4073							width: size,
4074							height: size,
4075							text: url
4076						}).css({
4077							position: 'absolute',
4078							display: 'none',
4079							zIndex: 10
4080						});
4081					}
4082			
4083					function showQR(container, link) {
4084						const linkRect = link[0].getBoundingClientRect();
4085						const containerWidth = container.outerWidth();
4086						const containerHeight = container.outerHeight();
4087			
4088						let left = linkRect.left;
4089						let top = linkRect.top - containerHeight - 10;
4090			
4091						if (left + containerWidth > $(window).width()) {
4092							left = linkRect.left + link.outerWidth() - containerWidth;
4093						}
4094			
4095						container.css({
4096							top: top + 'px',
4097							left: left + 'px',
4098							display: 'block',
4099							position: 'fixed'
4100						});
4101			
4102						activeQR = container;
4103					}
4104			
4105					function hideQR(container) {
4106						container.css({
4107							display: 'none'
4108						});
4109			
4110						if (activeQR && container.is(activeQR)) {
4111							activeQR = null;
4112						}
4113					}
4114					
4115					$(window).off('scroll.hideQR').on('scroll.hideQR', function () {
4116						if (activeQR) {
4117							activeQR.hide();
4118							activeQR = null;
4119						}
4120					});
4121				});
4122			});
4123		}
4124	};
4125	
4126	
4127	
4128	lpc_template.queue.rowMenu = function ($self) {
4129		let $block = $self.find('.lpc-row-menu');
4130	
4131		function rowMenuItems() {
4132			$block.each(function () {
4133				let $this = $(this);
4134				let $menu = $this.find('.lpc-menu-horizontal__list');
4135				let $toggleButton = $this.find('.lpc-menu-horizontal__more');
4136	
4137				let hideText = document.querySelector('html').getAttribute('lang') === 'ru' ? 'Скрыть' : 'Hide';
4138				let currentText = document.querySelector('html').getAttribute('lang') === 'ru' ? 'Ещё' : 'Show more';
4139	
4140				let $insTextButton = $toggleButton.find('ins');
4141				let $hiddenItems = $menu.find('li:not(.lpc-menu-horizontal__more):hidden');
4142				
4143				if ($hiddenItems.length) {
4144					$toggleButton.addClass('show');
4145				}
4146				
4147				$toggleButton.off('click').on('click', function () {
4148					$toggleButton.toggleClass('active');
4149					$menu.toggleClass('lpc-menu-horizontal__list--show-items');
4150					$insTextButton.text($toggleButton.hasClass('active') ? hideText : currentText);
4151				});
4152			});
4153		}
4154	
4155		rowMenuItems();
4156	
4157		document.addEventListener('dataMediaSourceChange', rowMenuItems);
4158	};
4159	
4160	
4161	lpc_template.queue.lpcFlexImageBlock = function ($self) {
4162		const paramsGet = new URLSearchParams(window.location.search);
4163		if(paramsGet.has('lpc_test')){	
4164			if(typeof ReactLPConstructor == 'object') {
4165				var $block = $self.find('.lpc-flexible-image-js') ? $self : $self.hasClass('.lpc-flexible-image-js');
4166			}else {
4167				var $block = $self.hasClass('.lpc-flexible-image-js') ? $self : $self.find('.lpc-flexible-image-js');
4168			}
4169	
4170			if($block.length) {
4171				$block.each(function () {
4172					let $item = $(this);
4173					let $itemId = $item.attr('id');			
4174					
4175					let $imgInit = `#${$itemId}.lpc-flexible-image-js`;
4176					
4177					function flexibleImage(parent){
4178						
4179						let blockParent = document.querySelector(parent);
4180						let inner = blockParent.querySelector('.lpc-flexible-image__inner-js');
4181						let list = blockParent.querySelector('.lpc-flexible-image__list-js'); 
4182						
4183						let wrap = blockParent.querySelector('.lpc-flexible-image__wrap-js');
4184						let wrapWidth = wrap.offsetWidth;
4185						
4186						let blockParentWidth = blockParent.offsetWidth;
4187						
4188						list.style.width = blockParentWidth + 'px';
4189						
4190						let inWrap = blockParent.querySelector('.lpc-flexible-image__in-wrap-js');
4191						
4192						let docWidth = document.documentElement.clientWidth;
4193						
4194						let WrapPos = wrap.getBoundingClientRect();
4195						
4196						
4197						//inWrap.style.marginLeft = -WrapPos.left + 'px';
4198						//inWrap.style.marginRight = -(WrapPos.right - wrapWidth) + 'px';
4199						
4200						let inWrapMarginLeft = WrapPos.left;
4201						let inWrapMarginRight = (docWidth - WrapPos.right);
4202						
4203						inWrap.style.marginLeft = -inWrapMarginLeft + 'px';
4204						inWrap.style.marginRight = -inWrapMarginRight + 'px';
4205						
4206						
4207						//let itemMarginRight = docWidth - slideWrap.getBoundingClientRect().right;
4208							
4209						inner.classList.add('load');
4210						
4211						
4212						let listGapStr = getComputedStyle(list).gridGap
4213						
4214						if(listGapStr === 'normal'){
4215							listGapStr = '32px';
4216						}
4217						
4218						let listGap = parseInt(listGapStr);
4219						
4220						
4221						let blockOutDivision = 8;
4222						let innerMargin = (wrapWidth - (listGap * 3)) / blockOutDivision;
4223						
4224						
4225						let innerMarginLeft = 0;
4226						let innerMarginRight = 0;
4227						
4228						if(inWrapMarginLeft !== inWrapMarginRight){
4229							innerMarginLeft = innerMargin - ((inWrapMarginLeft - inWrapMarginRight) / 2);
4230							innerMarginRight = innerMargin + ((inWrapMarginLeft - inWrapMarginRight) / 2);
4231						}  else {
4232							innerMarginLeft = innerMargin;
4233							innerMarginRight = innerMargin;
4234						}
4235						
4236						inner.style.marginLeft = -innerMarginLeft + 'px';
4237						inner.style.marginRight = -innerMarginRight + 'px';
4238						
4239						let innerWidth = inner.offsetWidth;
4240						let innerHeight = inner.offsetHeight;
4241						
4242						let listStageWidth = innerWidth - blockParentWidth;
4243						
4244						let images = blockParent.querySelectorAll('.lpc-flexible-image__image-js');
4245						
4246						let miniImageWidth = (blockParentWidth - listGap * 3) / 4;
4247						
4248						
4249						list.style.gridTemplateColumns = miniImageWidth + 'px ' + 'auto ' + 'auto ' + miniImageWidth + 'px';
4250						
4251						if(images[0]){
4252						
4253							let imageBig = images[0];
4254							
4255							if(imageBig.classList.contains('_1_1')) {
4256								
4257								imageBig.style.height = blockParentWidth / 2  + 'px';
4258								
4259							} else if (imageBig.classList.contains('_4_3h')) {
4260								
4261								
4262								imageBig.style.height = blockParentWidth * 3 / 8 + 'px';
4263								
4264							} else if (imageBig.classList.contains('_3_2h')) {
4265								
4266								imageBig.style.height = blockParentWidth / 3 + 'px';
4267								
4268							} else if (imageBig.classList.contains('_16_9h')) {
4269							
4270								
4271								imageBig.style.height = blockParentWidth * 9 / 30 + 'px';
4272								
4273							} else if (imageBig.classList.contains('_4_3v')) {
4274							
4275								
4276								imageBig.style.height = blockParentWidth * 2 / 3 + 'px';
4277								
4278							} else if (imageBig.classList.contains('_3_2v')) {
4279							
4280								
4281								imageBig.style.height = blockParentWidth * 3 / 4 + 'px';
4282								
4283							} else if (imageBig.classList.contains('_16_9v')) {
4284							
4285								
4286								imageBig.style.height = blockParentWidth * 8 / 9 + 'px';
4287								
4288							}
4289							
4290							
4291							
4292						}
4293						
4294						let heightStep = 0;
4295						
4296						heightStep = 40;
4297						
4298						
4299						function updateHeightStep() {
4300						    const decorWrap = document.querySelector('.decor-wrap');
4301						    if (decorWrap) {
4302						        const mediaSource = decorWrap.getAttribute('data-media-source');
4303						        if (mediaSource === 'media-xl' || mediaSource === 'media-lg' || mediaSource === 'media-md') {
4304						            heightStep = 40;
4305						        } else if (mediaSource === 'media-sm' || mediaSource === 'media-xs') {
4306						            heightStep = 60;
4307						        }
4308						    }
4309						}
4310						
4311						// Наблюдатель за изменениями атрибута data-media-source
4312						const observer = new MutationObserver(updateHeightStep);
4313						
4314						// Начало наблюдения за элементом
4315						const decorWrap = document.querySelector('.decor-wrap');
4316						if (decorWrap) {
4317						    observer.observe(decorWrap, {
4318						        attributes: true, // Наблюдаем за изменениями атрибутов
4319						        attributeFilter: ['data-media-source'] // Фильтруем только изменения атрибута data-media-source
4320						    });
4321						}
4322						
4323						// Вызов функции для первоначальной установки значения
4324						updateHeightStep();
4325						
4326						
4327						
4328						
4329						let heightStepArr = [heightStep, heightStep - 10, heightStep - 20, heightStep - 30]
4330						
4331						
4332						let listNewWidth = blockParentWidth;
4333						
4334						let windowHeight = document.documentElement.clientHeight;
4335						
4336						let topStagePercent = 0;
4337						
4338						let debounceTimer;
4339						
4340						window.addEventListener('scroll', function(event){
4341							clearTimeout(debounceTimer);
4342							
4343							debounceTimer = setTimeout(function () {
4344								updateListWidth()
4345							}, 5);
4346						})
4347						
4348						updateListWidth()
4349						
4350						function updateListWidth() {
4351							topStagePercent = Math.round(list.getBoundingClientRect().top / windowHeight * 100);
4352						
4353							
4354							if(inner.classList.contains('_rotate_left')){
4355								
4356								if(topStagePercent < heightStepArr[0] && topStagePercent >= heightStepArr[1]){
4357									list.style.width = listNewWidth + (listStageWidth / 4)  + 'px';
4358									inner.style.transform = 'rotate(-' + 1 + 'deg)';
4359									
4360								} else if (topStagePercent < heightStepArr[1] && topStagePercent >= heightStepArr[2])	{	
4361									list.style.width = listNewWidth + (listStageWidth / 2)  + 'px';
4362									inner.style.transform = 'rotate(-' + 2 + 'deg)';
4363									
4364								} else if (topStagePercent < heightStepArr[2] && topStagePercent >= heightStepArr[3])	{
4365									list.style.width = listNewWidth + (listStageWidth / 4 * 3)  + 'px';
4366									inner.style.transform = 'rotate(-' + 3 + 'deg)';
4367									
4368								} else if (topStagePercent < heightStepArr[3])	{
4369									list.style.width = listNewWidth + listStageWidth  + 'px';
4370									inner.style.transform = 'rotate(-' + 4 + 'deg)';
4371									
4372								} else {
4373									listNewWidth = blockParentWidth
4374									list.style.width = listNewWidth + 'px';
4375									inner.style.transform = 'rotate(' + 0 + 'deg)';
4376									
4377								}
4378								
4379							} else if(inner.classList.contains('_rotate_right')){
4380							
4381								if(topStagePercent < heightStepArr[0] && topStagePercent >= heightStepArr[1]){
4382									list.style.width = listNewWidth + (listStageWidth / 4)  + 'px';
4383									inner.style.transform = 'rotate(' + 1 + 'deg)';
4384									
4385								} else if (topStagePercent < heightStepArr[1] && topStagePercent >= heightStepArr[2])	{	
4386									list.style.width = listNewWidth + (listStageWidth / 2)  + 'px';
4387									inner.style.transform = 'rotate(' + 2 + 'deg)';
4388									
4389								} else if (topStagePercent < heightStepArr[2] && topStagePercent >= heightStepArr[3])	{
4390									list.style.width = listNewWidth + (listStageWidth / 4 * 3)  + 'px';
4391									inner.style.transform = 'rotate(' + 3 + 'deg)';
4392									
4393								} else if (topStagePercent < heightStepArr[3])	{
4394									list.style.width = listNewWidth + listStageWidth  + 'px';
4395									inner.style.transform = 'rotate(' + 4 + 'deg)';
4396									
4397								} else {
4398									listNewWidth = blockParentWidth
4399									list.style.width = listNewWidth + 'px';
4400									inner.style.transform = 'rotate(' + 0 + 'deg)';
4401									
4402								}
4403								
4404							} else {
4405							
4406								
4407								if(topStagePercent < heightStepArr[0] && topStagePercent >= heightStepArr[1]){
4408									list.style.width = listNewWidth + (listStageWidth / 4)  + 'px';
4409									
4410								} else if (topStagePercent < heightStepArr[1] && topStagePercent >= heightStepArr[2])	{	
4411									list.style.width = listNewWidth + (listStageWidth / 2)  + 'px';
4412									
4413								} else if (topStagePercent < heightStepArr[2] && topStagePercent >= heightStepArr[3])	{
4414									list.style.width = listNewWidth + (listStageWidth / 4 * 3)  + 'px';
4415									
4416								} else if (topStagePercent < heightStepArr[3])	{
4417									list.style.width = listNewWidth + listStageWidth  + 'px';
4418									
4419								} else {
4420									listNewWidth = blockParentWidth
4421									list.style.width = listNewWidth + 'px';
4422									
4423								}
4424								
4425							}
4426						}
4427							
4428					}
4429	
4430	
4431					if (s3LP.is_cms) {
4432						if(document.querySelector($imgInit)){	
4433						
4434							document.addEventListener('lpcLoadingDone', function(){
4435								flexibleImage($imgInit);
4436							});
4437							
4438							setTimeout(function(){
4439								flexibleImage($imgInit);
4440							}, 1000)
4441								
4442						}
4443						
4444					}else{
4445						document.addEventListener('lpc_init_after', function () {
4446							let lpc_block = document.querySelector($imgInit);
4447							
4448							if (lpc_block) {
4449						        let observer = new IntersectionObserver((entries, observer) => {
4450						            entries.forEach(entry => {
4451						                if (entry.isIntersecting) {
4452						                    flexibleImage($imgInit);
4453						                    observer.unobserve(entry.target); // Остановить наблюдение после первого появления
4454						                }
4455						            });
4456						        }, { threshold: 0.1 }); // Запускать, когда хотя бы 10% блока в зоне видимости
4457						
4458						        observer.observe(lpc_block);
4459						    }
4460						});
4461						
4462						// Отслеживание изменения размера окна
4463						let currentWidth = window.innerWidth;
4464						
4465						window.addEventListener('resize', function () {
4466							
4467							setTimeout(function(){
4468							    if (window.innerWidth !== currentWidth) {
4469							        currentWidth = window.innerWidth;
4470							        let lpc_block = document.querySelector($imgInit);
4471							
4472							        if (lpc_block) {
4473							            let observer = new IntersectionObserver((entries, observer) => {
4474							                entries.forEach(entry => {
4475							                    if (entry.isIntersecting) {
4476							                        flexibleImage($imgInit);
4477							                        observer.unobserve(entry.target); // Остановить наблюдение после первого появления
4478							                    }
4479							                });
4480							            }, { threshold: 0.1 });
4481							
4482							            observer.observe(lpc_block);
4483							        }
4484							    }
4485							}, 500)
4486						    
4487						}, true);
4488						
4489					}
4490				});
4491			}
4492		}
4493	}	
4494	
4495	
4496	lpc_template.queue.lpcSliderMagic = function ($self) {
4497		
4498			//var $block = $self.hasClass('.lpc-flexible-image-js') ? $self : $self.find('.lpc-flexible-image-js');
4499	var $block = $self.hasClass('magic-slider') ? $self : $self.find('.magic-slider');
4500	if($block.length) {
4501		
4502		$block.each(function () {
4503			
4504			let $item = $(this);
4505			let $itemId = $item.attr('id');		
4506			
4507			let $sliderMagic = `#${$itemId}.magic-slider`;
4508
4509			function sliderInit(parent){
4510		
4511				let sliderBlock = document.querySelector(parent);
4512				
4513				let decorWrap = document.querySelector('.decor-wrap');
4514				
4515				let mediaSource = decorWrap.getAttribute('data-media-source');
4516				
4517				if (!sliderBlock) return; // Проверка на существование элемента
4518				
4519				let sliderTrigger = Number(sliderBlock.getAttribute('data-trigger-hook'));
4520				
4521				let sliderContainer = sliderBlock.querySelector('.lpc-prods-m__magic-slider-container');
4522				
4523				let slider = sliderBlock.querySelector('.lpc-prods-m__magic-slider');
4524				
4525				let scrollWidth = 0;
4526				
4527				let slideBox = sliderBlock.querySelector('.lpc-prods-m__wrap-box');
4528				
4529				let sliderTitle = sliderBlock.querySelector('.magic-slider-header');
4530				
4531				//let sliderContainerWidth = sliderContainer;
4532				//слайды
4533				let slideItem = sliderBlock.querySelectorAll('.lpc-prods-m__magic-slide');
4534				
4535				//Счетчики 
4536				let counterIndex = sliderBlock.querySelector('.magic-slider__index');
4537				let totalItems = slideItem.length;
4538				//Счетчики 
4539				
4540				// Количество слайдов
4541				let slideCount = slideItem.length;
4542				//console.log(sliderTrigger)
4543				
4544				let progress = 0;
4545				
4546				let itemGap = 0;
4547				
4548				let slideWrap = sliderBlock.querySelector('.lpc-magic-full-width-init');
4549				
4550				
4551				function sliderInitInter() {	
4552						
4553						let slideWidth = slideWrap.offsetWidth;
4554						
4555						let docWidth = document.documentElement.clientWidth;
4556						
4557						//let itemMargin = (docWidth - slideWidth) / 2;
4558						
4559						let itemMarginLeft = slideWrap.getBoundingClientRect().left;
4560						
4561						//let itemMarginRight = slideWrap.getBoundingClientRect().right - slideWidth
4562						let itemMarginRight = docWidth - slideWrap.getBoundingClientRect().right;
4563						
4564						/*if(sliderBlock.classList.contains('magic-slider-full-width')){
4565							slideBox.style.marginLeft = '-' + itemMargin + 'px';
4566							slideBox.style.marginRight = '-' + itemMargin + 'px';
4567						}
4568						slideBox.style.marginLeft = '-' + itemMargin + 'px';
4569						slideBox.style.marginRight = '-' + itemMargin + 'px';*/
4570						
4571						slideBox.style.marginLeft = '-' + itemMarginLeft + 'px';
4572						slideBox.style.marginRight = '-' + itemMarginRight + 'px';
4573						
4574						/*if(!sliderBlock.classList.contains('magic-slider-full-width') && slideBox.classList.contains('magic-slider-container-block')){
4575							slideBox.style.marginLeft = 0;
4576							slideBox.style.marginRight = 0;
4577						}*/
4578						
4579						// Элементы
4580						
4581						if(sliderTitle){
4582							
4583							
4584							if(!sliderBlock.classList.contains('magic-slider-full-width')){
4585								sliderTitle.style.width = slideWidth + 'px';
4586								sliderTitle.style.marginLeft = itemMarginLeft + 'px';
4587							}
4588							
4589							if(!sliderBlock.classList.contains('magic-slider-full-width') && slideBox.classList.contains('magic-slider-container-block')){
4590								sliderTitle.style.marginLeft = 0;
4591							}
4592							
4593							if(sliderBlock.classList.contains('magic-slider-full-width') && slideBox.classList.contains('magic-slider-container-block')){
4594								sliderTitle.style.width = slideWidth + 'px';
4595								sliderTitle.style.marginLeft = itemMarginLeft + 'px';
4596							}
4597						}
4598						
4599						let itemWidth = 0;
4600						
4601						let coefficient = 0;
4602						
4603						/*if(sliderBlock.classList.contains('magic-slider-middle') && decorWrap.getAttribute('data-media-source') !== 'media-xs'){
4604							itemWidth = slideWidth / 3 * 2;
4605							coefficient = itemWidth / 2
4606							
4607						} else if (sliderBlock.classList.contains('magic-slider-small') && decorWrap.getAttribute('data-media-source') !== 'media-xs'){
4608							itemWidth = slideWidth / 2;
4609							coefficient = itemWidth
4610						} else {
4611							itemWidth = slideWidth;
4612						}*/
4613						
4614						if(sliderBlock.classList.contains('magic-slider-middle') && decorWrap.getAttribute('data-media-source') !== 'media-xs'){
4615						    itemWidth = slideWidth / 3 * 2;
4616						    coefficient = itemWidth / 2
4617						    
4618						} else if (sliderBlock.classList.contains('magic-slider-small')){
4619						
4620						    if (decorWrap.getAttribute('data-media-source') === 'media-xs'){
4621						        itemWidth = slideWidth;
4622						
4623						    } else if(decorWrap.getAttribute('data-media-source') === 'media-sm'){
4624						        itemWidth = slideWidth / 4 * 3;
4625						    coefficient = itemWidth / 3        
4626						    } else{
4627						        itemWidth = slideWidth / 2;
4628						        coefficient = itemWidth
4629						    }
4630						} else {
4631						    itemWidth = slideWidth;
4632						}
4633						
4634						
4635						let slideItemMarginLeft = 0;
4636						
4637						slideItemMarginLeft = parseInt(getComputedStyle(slideItem[0]).marginLeft);
4638						
4639						//let itemGap = 0;
4640						
4641						for(let i = 0; i < slideItem.length - 1; i++){
4642							itemGap += parseInt(getComputedStyle(slideItem[i]).marginRight);
4643						}
4644						
4645						//если контейнер и не на всю ширину блок
4646						
4647						if(!sliderBlock.classList.contains('magic-slider-full-width') && slideBox.classList.contains('magic-slider-container-block')){
4648						
4649							itemWidth = itemWidth - slideItemMarginLeft;
4650							
4651						}
4652						
4653						//настройка максимальной ширины слайда чтобы высота слайда не превышала 78vh
4654						
4655						let itemMaxHeight = window.innerHeight * 0.78;
4656						let aspectRatio = 16 / 9;
4657						
4658						let itemMaxWidth = itemMaxHeight * aspectRatio;
4659						
4660						let itemsCountWidth = 0
4661						let itemMathWidth = 0;
4662						let itemCount = 0;
4663						
4664						function slideSheetTarget(){
4665							slider.addEventListener('click', function(event){
4666								
4667								if(event.target.classList.contains('magic-item-sheet-btn')){
4668									let sheetBtn = event.target;
4669									let itemSheetContainer = sheetBtn.closest('.magic-item-column-slide');
4670									let sheet = itemSheetContainer.querySelector('.magic-item-sheet');
4671									let sheetClose = itemSheetContainer.querySelector('.magic-item-sheet-close');
4672									let sheetContainer = itemSheetContainer.querySelector('.magic-item-column-text');
4673									let itemSheetImage = itemSheetContainer.querySelector('.magic-item-column-image');
4674									
4675									let sheetContainerHeight = sheetContainer.offsetHeight;
4676									sheetContainer.style.minHeight = sheetContainerHeight + 'px';
4677									sheet.classList.remove('hidden-text');
4678									itemSheetContainer.classList.add('active');
4679									itemSheetImage.style.opacity = 0;
4680									
4681									/*************************************/
4682									
4683									if(progress !== 0 && progress !== 1){
4684										let transformMatrix = window.getComputedStyle(slider).transform;
4685										let translateX = 0;
4686										
4687										if (transformMatrix !== 'none') {
4688										    const matrixValues = transformMatrix.match(/matrix\((.+)\)/)[1].split(', ');
4689										    translateX = parseFloat(matrixValues[4]); 
4690										}
4691										
4692										/*let progressStatus = Math.round(progress * 100);
4693										
4694										
4695										//let itemScrollAmount = translateX;
4696										
4697										let itemScrollAmount = 0;
4698										
4699										//let scrollWidth = sliderBlock.scene.duration();
4700										
4701										let rect = itemSheetContainer.getBoundingClientRect();
4702									    let leftDistance = rect.left; // Расстояние от левого края экрана
4703									    let rightDistance = window.innerWidth - rect.right; // Расстояние от правого края экрана
4704									
4705									    //console.log("Левый край: " + leftDistance + "px, Правый край: " + rightDistance + "px");
4706									    
4707									    let windowWidth = document.documentElement.clientWidth;
4708									    
4709									    //console.log("Ширина viewport " + windowWidth)
4710									    
4711									    let itemSheetContainerWidth = itemSheetContainer.offsetWidth;
4712									    
4713									    //console.log("Ширина слайда " + itemSheetContainerWidth)
4714									    
4715									    let itemSheetContainerCenter = (windowWidth - itemSheetContainerWidth) / 2
4716									    
4717									    //console.log("количество пикселей для центровки " + itemSheetContainerCenter)
4718									    //console.log("полоса прокрутки " + scrollWidth)
4719									    
4720									    if(leftDistance > rightDistance){
4721									    	itemScrollAmount = leftDistance - itemSheetContainerCenter;
4722									    	
4723									    	//console.log("нужно прокрутить вправо на " + itemScrollAmount)
4724									    } else if(rightDistance > leftDistance){
4725									    	
4726									    	itemScrollAmount = rightDistance - itemSheetContainerCenter
4727									    	itemScrollAmount = -itemScrollAmount
4728									    
4729									    	//console.log("нужно прокрутить влево на " + itemScrollAmount)
4730									    }
4731										
4732										//itemScrollAmount = itemSheetContainer.offsetWidth + parseInt(getComputedStyle(itemSheetContainer).marginRight);
4733										
4734										let itemsSheet = [...slider.children]; // Преобразуем в массив
4735										
4736										// Определяем, первый ли это элемент
4737								        /*if (itemsSheet[0] === itemSheetContainer) {
4738								            console.log('Это первый элемент:');
4739								        }*/
4740								        // Определяем, последний ли это элемент
4741								        /*if (itemsSheet[itemsSheet.length - 1] === itemSheetContainer) {
4742								            console.log('Это последний элемент:');
4743								        }*/
4744										
4745										
4746										window.scrollBy({ top: itemScrollAmount, left: 0, behavior: "smooth" });
4747										//console.log(itemScrollAmount)
4748									}
4749									
4750									/*************************************/
4751									
4752									sheetClose.addEventListener('click', function(event){
4753										sheetContainer.style.minHeight = 0;
4754										sheet.classList.add('hidden-text');
4755										itemSheetContainer.classList.remove('active');
4756										itemSheetImage.style.opacity = 1;
4757									});
4758									
4759									window.addEventListener('resize', function(){
4760										sheetContainer.style.minHeight = 0;
4761										sheet.classList.add('hidden-text');
4762										itemSheetContainer.classList.remove('active');
4763										itemSheetImage.style.opacity = 1;
4764									})
4765									
4766									document.addEventListener('click', function(e){
4767										if (!e.target.closest('.lpc-prods-m-item')) {
4768											sheetContainer.style.minHeight = 0;
4769											sheet.classList.add('hidden-text');
4770											itemSheetContainer.classList.remove('active');
4771											itemSheetImage.style.opacity = 1;
4772										}
4773									});
4774								}
4775								
4776								
4777							});
4778						}
4779						
4780						slideSheetTarget()
4781						
4782						for(let i = 0; i < slideItem.length; i++){
4783							slideItem[i].style.width = itemWidth + 'px';
4784							slideItem[i].style.maxWidth = itemMaxWidth + 'px';
4785							
4786							
4787							let slideItemRow = slideItem[i].querySelector('.magic-slide-item-row');
4788								
4789							let slideItemRowHeight = slideItemRow.offsetHeight;
4790							
4791							let slideItemRowImage = slideItemRow.querySelector('.magic-item-column-image')
4792							let slideItemRowText = slideItemRow.querySelector('.magic-item-column-text')
4793							
4794							if (slideItemRowImage){
4795								let slideItemRowImageHeight = slideItemRowImage.offsetHeight;
4796								
4797								let newWidth = 0;
4798								
4799								if(decorWrap.getAttribute('data-media-source') === 'media-xs'){
4800								
4801									
4802									let slideItemRowTextTitle = slideItemRow.querySelector('.magic-item-column-text-title');
4803									let slideItemRowTextDesc = slideItemRow.querySelector('.magic-item-column-text-desc');
4804									let slideItemRowTextMobHeight = 0;
4805									
4806									if (slideItemRowTextTitle){
4807										let slideItemRowTextTitleHeight = slideItemRowTextTitle.offsetHeight;
4808										let slideItemRowTextTitleMargin = parseInt(getComputedStyle(slideItemRowTextTitle).marginBottom)
4809										
4810										slideItemRowTextMobHeight += slideItemRowTextTitleHeight + slideItemRowTextTitleMargin
4811									}
4812									
4813									if (slideItemRowTextDesc){
4814										let slideItemRowTextDescHeight = slideItemRowTextDesc.offsetHeight;
4815										
4816										slideItemRowTextMobHeight += slideItemRowTextDescHeight
4817										
4818									}
4819									
4820									if(slideItemRowImageHeight + slideItemRowTextMobHeight > slideItemRowHeight){
4821										
4822										while (slideItemRowImageHeight + slideItemRowTextMobHeight > slideItemRowHeight) {
4823											newWidth = slideItem[i].offsetWidth;
4824											slideItem[i].style.width = newWidth - 10 + "px";
4825											
4826											slideItemRowImageHeight = slideItemRowImage.offsetHeight;
4827											slideItemRowHeight = slideItemRow.offsetHeight;
4828											
4829											if(slideItemRowImageHeight + slideItemRowTextMobHeight <= slideItemRowHeight){
4830											
4831												break
4832											
4833											}
4834											
4835										}
4836									
4837									}
4838								
4839								
4840									
4841								} else {
4842								
4843									if(slideItemRowImageHeight > slideItemRowHeight){
4844										
4845										while (slideItemRowImageHeight > slideItemRowHeight) {
4846											newWidth = slideItem[i].offsetWidth;
4847											slideItem[i].style.width = newWidth - 10 + "px";
4848											
4849											slideItemRowImageHeight = slideItemRowImage.offsetHeight;
4850											slideItemRowHeight = slideItemRow.offsetHeight;
4851											
4852											if(slideItemRowImageHeight <= slideItemRowHeight){
4853											
4854												break
4855											
4856											}
4857											
4858										}
4859										
4860									}
4861								}
4862								
4863							}
4864							
4865							
4866							itemsCountWidth = itemsCountWidth + slideItem[i].offsetWidth;
4867							++itemCount;
4868							
4869							
4870						}
4871						
4872						
4873						itemMathWidth = itemsCountWidth / itemCount;
4874						
4875						
4876						
4877						if(sliderBlock.classList.contains('magic-slider-full-width')){
4878							
4879							let boxWidth = slideBox.clientWidth;
4880							sliderContainer.style.maxWidth = boxWidth + 'px';
4881						
4882							//scrollWidth = (itemMathWidth  * (slideCount - 1)) - (itemMargin * 2) + (slideItemMarginLeft * 2) + itemGap - coefficient - (itemWidth - itemMathWidth);
4883							
4884							scrollWidth = (itemMathWidth  * (slideCount - 1)) - (itemMarginLeft + itemMarginRight) + (slideItemMarginLeft * 2) + itemGap - coefficient - (itemWidth - itemMathWidth);
4885							
4886							
4887							if(slideBox.classList.contains('magic-slider-container-block')){
4888								
4889								let boxWidth = slideBox.clientWidth;
4890								sliderContainer.style.maxWidth = boxWidth + 'px';
4891								
4892								slideItem[0].style.marginLeft = itemMarginLeft + 'px';
4893								scrollWidth = itemMathWidth  * (slideCount - 1) + itemGap - coefficient - (itemWidth - itemMathWidth);
4894								
4895							}
4896							
4897						} else {
4898							
4899							/*if(!sliderBlock.classList.contains('magic-slider-full-width') && slideBox.classList.contains('magic-slider-container-block')){*/
4900							if(slideBox.classList.contains('magic-slider-container-block')){
4901							
4902								slideBox.style.marginLeft = 0;
4903								slideBox.style.marginRight = 0;
4904								
4905								let boxWidth = slideBox.clientWidth;
4906								
4907								sliderContainer.style.maxWidth = boxWidth + 'px';
4908								
4909								
4910								//scrollWidth = itemMathWidth  * (slideCount - 1) + itemGap - coefficient + (slideItemMarginLeft * 1);
4911								scrollWidth = itemMathWidth  * (slideCount - 1) + itemGap - coefficient - (itemWidth - itemMathWidth) + slideItemMarginLeft;
4912								
4913							
4914							} else {
4915								
4916								let boxWidth = slideBox.clientWidth;
4917								sliderContainer.style.maxWidth = boxWidth + 'px';
4918								
4919								slideItem[0].style.marginLeft = itemMarginLeft + 'px';
4920								scrollWidth = itemMathWidth  * (slideCount - 1) + itemGap - coefficient - (itemWidth - itemMathWidth);
4921								
4922							}
4923							
4924							
4925						}
4926				}		
4927				
4928				
4929				function sliderInitRemoveStyle(){
4930					slideBox.removeAttribute('style');
4931					
4932					if(sliderTitle) {
4933						sliderTitle.removeAttribute('style');
4934					}
4935					
4936					
4937					for(let i = 0; i < slideItem.length; i++){
4938						slideItem[i].removeAttribute('style');
4939					}
4940				}
4941				
4942				//тут был расчет ширины блоков, уехал на верх
4943				
4944				let controller = null;
4944 // Контроллер объявляем глобально
4945				let scene = null;
4946				
4947				destroySlider();
4948				
4949				function initSlider() {
4950				
4951					if(scrollWidth > 0) {
4952				
4953						controller = new ScrollMagic.Controller();
4954			    		sliderBlock.controller = controller;
4955			    		
4956			    		scene = new ScrollMagic.Scene({
4957					        triggerElement: sliderContainer,
4958					        duration: scrollWidth,
4959					        triggerHook: sliderTrigger,
4960					        offset: 0
4961					    })
4962					    .setPin(sliderContainer)
4963					    .on("progress", function (event) {
4964						    progress = event.progress;
4965						    
4966						    let startZone = 0.1; // 10% в начале (ничего не движется)
4967						    let endZone = 0.1;   // 10% в конце (ничего не движется)
4968						    
4969						    let adjustedProgress = 0;
4970						
4971						    if (progress < startZone) {
4972						        adjustedProgress = 0;
4973						    } else if (progress > (1 - endZone)) {
4974						        adjustedProgress = 1;
4975						    } else {
4976						        adjustedProgress = (progress - startZone) / (1 - startZone - endZone);
4977						    }
4978						
4979						    let transformPos = Math.round(-scrollWidth * adjustedProgress);
4980						    
4981						    slider.style.transform = "translateX(" + transformPos + "px)";
4982						    
4983						    // Обновление счетчика страниц на основе скорректированного прогресса
4984						    if (counterIndex) {
4985						        let currentIndex = Math.round(adjustedProgress * (totalItems - 1)) + 1;
4986						        if (counterIndex.textContent != currentIndex) {
4987						            counterIndex.textContent = currentIndex;
4988						        }
4989						    }
4990						})
4991					    .addTo(controller);
4992					
4993					    sliderBlock.scene = scene; // Сохраняем сцену
4994				    
4995				    } else {
4996				    	//console.log('off')
4997				    	
4998				    	sliderContainer.style.height = 'auto';
4999				    }
5000				
5001				}
5002				
5003				
5004				// Функция для уничтожения слайдера
5005				function destroySlider() {
5006				    if (sliderBlock.controller) {
5007				        sliderBlock.controller.destroy(true);
5008				        sliderBlock.controller = null;
5009				        slider.style.transform = "translateX(" + 0 + ")";
5010				        scene = null;
5011				    }
5012				}
5013				
5014				
5015				// Функция для обработки изменений атрибута
5016				function handleAttributeChange() {
5017				    mediaSource = decorWrap.getAttribute('data-media-source');
5018				    
5019				    if(sliderBlock.classList.contains('lpc_scroll_disable')) {
5020				
5021					    if (mediaSource === 'media-xs' || mediaSource === 'media-md' || mediaSource === 'media-sm') {
5022					    	
5023					    	sliderInitRemoveStyle()
5024					        destroySlider();
5025					        
5026					        if(sliderBlock.classList.contains('magic-slider-full-width')) {//Для адаптации , когда блок на всю ширину
5027						        let slideWidth = slideWrap.offsetWidth;
5028								let docWidth = document.documentElement.clientWidth;
5029								let itemMarginLeft = slideWrap.getBoundingClientRect().left;
5030								let itemMarginRight = docWidth - slideWrap.getBoundingClientRect().right;
5031								slideBox.style.marginLeft = '-' + itemMarginLeft + 'px';
5032								slideBox.style.marginRight = '-' + itemMarginRight + 'px';
5033					        }
5034					    } else if (mediaSource === 'media-xl' || mediaSource === 'media-lg') {
5035					        if (!sliderBlock.controller) {
5036					        	sliderInitInter()
5037					            initSlider();
5038					        }
5039					    }
5040					    
5041					} else {
5042						if (!sliderBlock.controller) {
5043				            
5044				            if (mediaSource === 'media-xs') {
5045				            
5046				             	sliderInitInter()
5047				            	initSlider();
5048			            	
5049			            	} else if (mediaSource === 'media-xl' || mediaSource === 'media-lg' || mediaSource === 'media-md' || mediaSource === 'media-sm') {
5050			            		sliderInitInter()
5051				            	initSlider();
5052			            	}
5053				            
5054				        }
5055					}
5056				}
5057				
5058				// Запускаем наблюдатель за атрибутами
5059				let observer = new MutationObserver(handleAttributeChange);
5060				observer.observe(decorWrap, { attributes: true, attributeFilter: ['data-media-source'] });
5061				
5062				// Запускаем слайдер, если сразу media-xl
5063				handleAttributeChange();
5064				
5065			}
5066
5067			if (s3LP.is_cms){
5068				
5069				if(document.querySelector($sliderMagic)){	
5070				
5071					document.addEventListener('lpcLoadingDone', function(){
5072						sliderInit($sliderMagic);
5073					});
5074					
5075					setTimeout(function(){
5076						sliderInit($sliderMagic);
5077					}, 1000)						
5078						
5079				}
5080				
5081			}else{
5082				
5083				document.addEventListener('lpc_init_after', function() {
5084					var sliderSelector = $sliderMagic;
5085					var sliderEl = document.querySelector(sliderSelector);
5086					if (!sliderEl) return; // если блока нет — выходим
5087					
5088					var sliderInitialized = false;
5089					
5090					// Функция для инициализации слайдера (однократно)
5091					function initSlider() {
5092						if (!sliderInitialized) {
5093							sliderInit(sliderSelector);
5094							sliderInitialized = true;
5095							// Если инициализация требуется только один раз, можно убрать слушатель скролла:
5096							window.removeEventListener('scroll', scrollHandler);
5097						}
5098					}
5099					
5100					// Проверяем, виден ли блок или уже был показан (например, если мы перезагрузили страницу ниже блока)
5101					function checkVisibility() {
5102						var rect = sliderEl.getBoundingClientRect();
5103						// Если верхняя граница блока меньше высоты окна – значит, блок либо виден, либо уже прошёл мимо
5104						if (rect.top < window.innerHeight) {
5105							initSlider();
5106						}
5107					}
5108					
5109					function scrollHandler() {
5110						checkVisibility();
5111					}
5112					
5113					// При загрузке страницы проверяем видимость блока
5114					checkVisibility();
5115					// Если блок ещё не был показан, следим за прокруткой
5116					window.addEventListener('scroll', scrollHandler);
5117					
5118					// При изменении размеров окна перезапускаем слайдер (как в исходном варианте)
5119					window.addEventListener('resize', function(){
5120						setTimeout(function(){
5121							// Если слайдер уже был инициализирован – обновляем его,
5122							// если ещё нет – проверяем видимость блока
5123							if (sliderInitialized) {
5124								sliderInit(sliderSelector);
5125							} else {
5126								checkVisibility();
5127							}
5128						}, 500);
5129					});
5130				});
5131
5132			
5133			}
5134		});
5135	}
5136	}	
5137	
5138	
5139	let bgWatchers = {};
5140
5141	lpc_template.queue.lpcDecorText = function($self) {
5142		var $block = $self.hasClass('lpc-elements-dynamic-headline') ? $self : $self.find('.lpc-elements-dynamic-headline');
5143		
5144		function initHeadline() {
5145			if($block.length) {
5146				$block.each(function () {
5147					let $item = $(this);
5148					let $itemId = $item.attr('id');
5149					let $title = `#${$itemId} .lpc-elements-dynamic-headline__title`;
5150					let $titleInit = `#${$itemId} .lpc-dynamic-title-init`;
5151					let $bgItem = `#${$itemId} .lp-block-bg_item`;
5152					let $overlayItem = `#${$itemId} .lp-block-overlay_item`;
5153					
5154	
5155					dynamicTextWidth($titleInit, $title);
5156	
5157					if (document.querySelector($title) && document.querySelector($title).classList.contains('bg_clip')) {
5158						dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5159					};
5160	
5161					let observerTitle = bindObserver($title, $titleInit, $bgItem, $overlayItem);
5162	
5163	
5164					// Отслеживание изменений фона
5165					if (document.querySelector($title) && document.querySelector($title).classList.contains('bg_clip')) {
5166						let bgPrev, ovPrev;
5167	
5168						if (bgWatchers[$itemId]) {
5169							clearInterval(bgWatchers[$itemId]);
5170						}
5171						
5172						bgWatchers[$itemId] = setInterval(() => {
5173							const t = document.querySelector($title);
5174							if (!t || !t.classList.contains('bg_clip')) return;
5175						
5176							const bg = document.querySelector($bgItem);
5177							const ov = document.querySelector($overlayItem);
5178							if (!bg || !ov) return;
5179						
5180							const bgNow = getComputedStyle(bg).background;
5181							const ovNow = getComputedStyle(ov).background;
5182						
5183							if ((bgPrev && bgPrev !== bgNow) || (ovPrev && ovPrev !== ovNow)) {
5184								dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5185							}
5186						
5187							bgPrev = bgNow;
5188							ovPrev = ovNow;
5189						}, 300);
5190					};
5191					
5192					$(document).on('click', '#publish_button, #cancel_all_button, .clear-control', function() {
5193						setTimeout(function () {
5194							// пересчёт размера
5195							dynamicTextWidth($titleInit, $title);
5196	
5197							// проверка фона
5198							dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5199					
5200							// перезапуск наблюдения
5201							if (observerTitle) observerTitle.disconnect();
5202							observerTitle = bindObserver($title, $titleInit, $bgItem, $overlayItem);
5203						}, 50);
5204					});
5205	
5206	
5207					// Для ЛПЦ
5208					function waitForStylesheet(callback, delay = 500) {
5209						const interval = setInterval(() => {
5210							if (document.getElementById('lpc-stylesheet')) {
5211								clearInterval(interval);
5212								setTimeout(callback, delay);
5213							}
5214						}, 250);
5215					}
5216	
5217					waitForStylesheet(() => {
5218						dynamicTextWidth($titleInit, $title);
5219					}, 500);
5220					
5221					if (!s3LP.is_cms) {
5222						let initTimeout;
5223						
5224						$(window).on('resize', function(){
5225							clearInterval(initTimeout);
5226	
5227							initTimeout = setTimeout(function(){
5228								dynamicTextWidth($titleInit, $title);
5229	
5230								if (document.querySelector($title) && document.querySelector($title).classList.contains('bg_clip')) {
5231									dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5232								};
5233							}, 50);
5234						});
5235					};
5236				});
5237			}
5238		};
5239	
5240		function bindObserver($title, $titleInit, $bgItem, $overlayItem) {
5241			let contentTitle = document.querySelector($title);
5242			if (!contentTitle) return;
5243		
5244			let observerTitle = new MutationObserver((mutations) => {
5245				mutations.forEach((mutation) => {
5246					if ($(mutation.target).closest('.lpc-dynamic-title-init').length) {
5247		
5248						if (mutation.type === "characterData" || mutation.type === "childList") {
5249							dynamicTextWidth($titleInit, $title);
5250	
5251							setTimeout(function () {
5252								let el = document.querySelector($title);
5253								if (el && el.classList.contains('bg_clip')) {
5254									dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5255								}
5256							}, 100);
5257						}
5258					}
5259				});
5260			});
5261		
5262			observerTitle.observe(contentTitle, {
5263				childList: true,
5264				subtree: true,
5265				characterData: true
5266			});
5267		
5268			return observerTitle;
5269		};
5270		
5271		function dynamicTextWidth(parent, child) {
5272			let $dynamicWrap = $(parent);
5273			let $dynamicTitle = $(child);
5274		
5275			let dynamicTitleMinSize = 2;
5276			let dynamicTitleMaxSize = 55;
5277		
5278			function isMobile() {
5279				return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(navigator.userAgent)
5280					|| window.matchMedia("(max-width: 768px)").matches;
5281			}
5282		
5283			if (isMobile()) {
5284				dynamicTitleMinSize = 4.2;
5285			} else {
5286				if ($dynamicWrap.hasClass('lpc-full-width-init')) {
5287					dynamicTitleMinSize = 3.2;
5288				} else {
5289					dynamicTitleMinSize = 2;
5290				}
5291			}
5292		
5293			// Для центрирования блока если полная ширина
5294			if ($dynamicWrap.hasClass('lpc-full-width-init')) {
5295				let $dynamicBlockWrap = $dynamicWrap.closest('.lpc-full-width');
5296				let $dynamicBlockIn = $dynamicWrap.closest('.lpc-elements-dynamic-headline__wrap');
5297				let viewportWidth = $(window).width();
5298				let dynamicWrapMargin = (viewportWidth - $dynamicBlockWrap.outerWidth()) / 2;
5299		
5300				$dynamicBlockIn.css({
5301					'margin-left': `-${dynamicWrapMargin}px`,
5302					'margin-right': `-${dynamicWrapMargin}px`
5303				});
5304			}
5305		
5306			let min = dynamicTitleMinSize;
5307			let max = dynamicTitleMaxSize;
5308			let attempts = 0;
5309			let maxAttempts = 20; // защита от проклятий
5310		
5311			$dynamicTitle.css('white-space', 'nowrap');
5312		
5313			while (attempts < maxAttempts) {
5314				let mid = (min + max) / 2;
5315				$dynamicTitle.css('font-size', mid + 'vw');
5316		
5317				if ($dynamicTitle.outerWidth() > $dynamicWrap.outerWidth()) {
5318					max = mid;  // слишком большой размер
5319				} else {
5320					min = mid;  // можно попробовать больше
5321				}
5322		
5323				attempts++;
5324			}
5325		
5326			$dynamicTitle.css('font-size', min + 'vw');
5327			$dynamicTitle.css('opacity', 1);
5328		
5329			// Если крошечный текст — ворочаем переносы
5330			if (min <= dynamicTitleMinSize + 0.2) {
5331				$dynamicTitle.css('white-space', 'normal');
5332			}
5333		};
5334	
5335	
5336		function dynamicTextBg(parent, child, overlays, overlayItem) {
5337			if (document.querySelector(parent)) {
5338				let dynamicWrap = document.querySelector(parent);
5339				let dynamicTitle = dynamicWrap.querySelector(child);
5340		
5341				let titleOverlays = dynamicWrap.querySelectorAll(overlays);
5342				let titleOverlayLast = titleOverlays[titleOverlays.length - 1]
5343				let titleOverlayItem = titleOverlayLast.querySelector(overlayItem);
5344		
5345				if (titleOverlayLast) {
5346		
5347					let titleOverlayItemBg = getComputedStyle(titleOverlayItem).backgroundImage;
5348					let titleOverlayItemBgCol = getComputedStyle(titleOverlayItem).backgroundColor;
5349					let titleOverlayLastBg = getComputedStyle(titleOverlayLast).backgroundImage;
5350		
5351		
5352					if (titleOverlayItemBg !== 'none') {
5353		
5354						let computedStyles = window.getComputedStyle(titleOverlayLast);
5355		
5356						let bgProperties = [
5357							'background-image',
5358							'background-position',
5359							'background-size',
5360							'background-repeat',
5361							'background-attachment'
5362						];
5363		
5364						bgProperties.forEach(function (properties) {
5365							dynamicTitle.style[properties] = computedStyles.getPropertyValue(properties);
5366		
5367						})
5368		
5369						dynamicTitle.style.backgroundImage = titleOverlayItemBg + ', ' + titleOverlayLastBg;
5370		
5371					} else if (titleOverlayItemBgCol !== 'transparent' && titleOverlayItemBgCol !== 'rgba(0, 0, 0, 0)' && titleOverlayItemBgCol !== 'rgba(255, 255, 255, 0)') {
5372		
5373						let computedStyles = window.getComputedStyle(titleOverlayLast);
5374		
5375		
5376						let bgProperties = [
5377							'background-image',
5378							'background-position',
5379							'background-size',
5380							'background-repeat',
5381							'background-attachment'
5382						];
5383		
5384						bgProperties.forEach(function (properties) {
5385							if (bgProperties !== 'background-image') {
5386								dynamicTitle.style[properties] = computedStyles.getPropertyValue(properties);
5387							}
5388						})
5389		
5390						dynamicTitle.style.backgroundImage = 'linear-gradient(to right,' + titleOverlayItemBgCol + ', ' + titleOverlayItemBgCol + ')' + ', ' + titleOverlayLastBg;
5391		
5392					} else if ((titleOverlayItemBgCol === 'transparent' || titleOverlayItemBgCol === 'rgba(0, 0, 0, 0)') && titleOverlayLastBg === 'none') {
5393		
5394						let rootStyles = getComputedStyle(document.documentElement); // :root стили
5395						let bgColor = rootStyles.getPropertyValue('--text-color-base').trim();
5396		
5397						dynamicTitle.style.backgroundColor = bgColor;
5398						dynamicTitle.style.backgroundImage = 'none';
5399		
5400		
5401					} else {
5402		
5403						let computedStyles = window.getComputedStyle(titleOverlayLast);
5404						let bgProperties = [
5405							'background-image',
5406							'background-position',
5407							'background-size',
5408							'background-repeat',
5409							'background-attachment'
5410						];
5411		
5412						bgProperties.forEach(function (properties) {
5413							if (bgProperties !== 'background-image') {
5414								dynamicTitle.style[properties] = computedStyles.getPropertyValue(properties);
5415							}
5416		
5417							let value = computedStyles.getPropertyValue(properties);
5418							if (properties === 'background-image' && value === 'none') {
5419								dynamicTitle.style.removeProperty('background-image');
5420							}
5421						})
5422					}
5423		
5424					if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
5425						dynamicTitle.style.backgroundAttachment = 'scroll';
5426					}
5427				}
5428			}
5429		};
5430	
5431		document.addEventListener("lpc_init_after", function () {
5432			if (s3LP.is_cms) {
5433				setTimeout(function(){
5434					initHeadline();
5435				}, 200)
5436			};
5437		});
5438	};
5439	
5440	
5441	/*lpc_template.queue.lpcDecorText = function ($self) {
5442		var $block = $self.hasClass('lpc-elements-dynamic-headline') ? $self : $self.find('.lpc-elements-dynamic-headline');
5443		
5444		//const paramsGet = new URLSearchParams(window.location.search);
5445		//if(paramsGet.has('lpc_test')){
5446			
5447			if($block.length) {
5448				$block.each(function () {
5449					let $item = $(this);
5450					let $itemId = $item.attr('id');
5451	
5452					let $title = `#${$itemId} .lpc-elements-dynamic-headline__title`;
5453					let $titleInit = `#${$itemId} .lpc-dynamic-title-init`;
5454					let $bgItem = `#${$itemId} .lp-block-bg_item`;
5455					let $overlayItem = `#${$itemId} .lp-block-overlay_item`;
5456	
5457	
5458					function dynamicTextBg(parent, child, overlays, overlayItem){
5459						
5460						if(document.querySelector(parent)){
5461							let dynamicWrap = document.querySelector(parent);
5462							let dynamicTitle = dynamicWrap.querySelector(child);
5463							
5464							let titleOverlays = dynamicWrap.querySelectorAll(overlays);
5465							let titleOverlayLast = titleOverlays[titleOverlays.length - 1]
5466							let titleOverlayItem = titleOverlayLast.querySelector(overlayItem);
5467						
5468							if (titleOverlayLast) {
5469								
5470								let titleOverlayItemBg = getComputedStyle(titleOverlayItem).backgroundImage;
5471								let titleOverlayItemBgCol = getComputedStyle(titleOverlayItem).backgroundColor;				
5472								let titleOverlayLastBg = getComputedStyle(titleOverlayLast).backgroundImage;
5473							
5474								
5475								if(titleOverlayItemBg !== 'none'){
5476									
5477									let computedStyles = window.getComputedStyle(titleOverlayLast);
5478	
5479									let bgProperties = [
5480										'background-image',
5481										'background-position',
5482										'background-size',
5483										'background-repeat',
5484										'background-attachment'
5485									];
5486	
5487									bgProperties.forEach(function(properties){
5488										dynamicTitle.style[properties] = computedStyles.getPropertyValue(properties);
5489										
5490									})
5491									
5492									dynamicTitle.style.backgroundImage = titleOverlayItemBg + ', ' + titleOverlayLastBg;
5493									
5494								} else if(titleOverlayItemBgCol !== 'transparent' && titleOverlayItemBgCol !== 'rgba(0, 0, 0, 0)' && titleOverlayItemBgCol !== 'rgba(255, 255, 255, 0)'){
5495									
5496									let computedStyles = window.getComputedStyle(titleOverlayLast);
5497	
5498								
5499									let bgProperties = [
5500										'background-image',
5501										'background-position',
5502										'background-size',
5503										'background-repeat',
5504										'background-attachment'
5505									];
5506									
5507									bgProperties.forEach(function(properties){
5508										if(bgProperties !== 'background-image'){
5509											dynamicTitle.style[properties] = computedStyles.getPropertyValue(properties);
5510										}
5511									})
5512									
5513									dynamicTitle.style.backgroundImage = 'linear-gradient(to right,' + titleOverlayItemBgCol + ', ' + titleOverlayItemBgCol + ')' + ', ' + titleOverlayLastBg;
5514									
5515								} else if((titleOverlayItemBgCol === 'transparent' || titleOverlayItemBgCol === 'rgba(0, 0, 0, 0)') && titleOverlayLastBg === 'none') {
5516								
5517									let rootStyles = getComputedStyle(document.documentElement); // :root стили
5518									let bgColor = rootStyles.getPropertyValue('--text-color-base-header').trim();
5519									
5520									dynamicTitle.style.backgroundColor = bgColor;
5521									dynamicTitle.style.backgroundImage = 'none';
5522									
5523									
5524								} else {
5525								
5526									let computedStyles = window.getComputedStyle(titleOverlayLast);
5527									let bgProperties = [
5528										'background-image',
5529										'background-position',
5530										'background-size',
5531										'background-repeat',
5532										'background-attachment'
5533									];
5534									
5535									bgProperties.forEach(function(properties){
5536										if(bgProperties !== 'background-image'){
5537											dynamicTitle.style[properties] = computedStyles.getPropertyValue(properties);
5538										}	
5539	
5540										let value = computedStyles.getPropertyValue(properties);
5541										if (properties === 'background-image' && value === 'none') {
5542											dynamicTitle.style.removeProperty('background-image');
5543										}
5544									})
5545								}
5546								
5547								if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
5548									dynamicTitle.style.backgroundAttachment = 'scroll';
5549								}	
5550							}
5551						}
5552					}
5553					
5554					function dynamicTextWidth(parent, child){
5555						if (typeof ReactLPConstructor == 'object') {
5556							if (document.querySelector(parent) && document.querySelector(child)) {
5557						        let dynamicWrap = document.querySelector(parent);
5558						        let dynamicTitle = dynamicWrap.querySelector(child);
5559						
5560						        let dynamicTitleMinSize = 3.2;
5561						        let dynamicTitleMaxSize = 55;
5562						
5563						        // Определение мобильного
5564						        function isMobile() {
5565						            return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(navigator.userAgent) 
5566						                   || window.matchMedia("(max-width: 768px)").matches;
5567						        }
5568						
5569						        if (isMobile()) {
5570						            dynamicTitleMinSize = 4.2;
5571						        } else {
5572						            if (dynamicWrap.classList.contains('lpc-full-width-init')) {
5573						                dynamicTitleMinSize = 3.2;
5574						            } else {
5575						                dynamicTitleMinSize = 2;
5576						            }
5577						        }
5578						
5579						        // Если full-width, задаем отступы
5580						        if (dynamicWrap.classList.contains('lpc-full-width-init')) {
5581						            let dynamicBlockWrap = dynamicWrap.closest('.lpc-full-width');
5582						            let dynamicBlockIn = dynamicWrap.closest('.lpc-elements-dynamic-headline__wrap');				
5583						            let viewportWidth = window.innerWidth;
5584						            let dynamicWrapMargin = (viewportWidth - dynamicBlockWrap.offsetWidth) / 2;
5585						
5586						            $(dynamicBlockIn).css({
5587						                'margin-left': '-' + dynamicWrapMargin + 'px',
5588						                'margin-right': '-' + dynamicWrapMargin + 'px'
5589						            });
5590						        }
5591						
5592						        // --- Новый способ подбора font-size ---
5593						        let wrapWidth = dynamicWrap.offsetWidth;
5594						        let titleWidth = dynamicTitle.scrollWidth; // берём полную ширину текста
5595						
5596						        if (titleWidth > 0) {
5597						            // вычисляем нужный font-size (в vw) пропорционально
5598						            let scale = wrapWidth / titleWidth;
5599						            let currentFontSize = parseFloat(getComputedStyle(dynamicTitle).fontSize);
5600						            let newFontSizeVW = ((currentFontSize * scale) / window.innerWidth) * 100;
5601						
5602						            // ограничиваем
5603						            if (newFontSizeVW < dynamicTitleMinSize) newFontSizeVW = dynamicTitleMinSize;
5604						            if (newFontSizeVW > dynamicTitleMaxSize) newFontSizeVW = dynamicTitleMaxSize;
5605						
5606						            dynamicTitle.style.fontSize = newFontSizeVW + 'vw';
5607						        }
5608						
5609						        dynamicTitle.style.opacity = 1;
5610						    }
5611						} else{
5612							if(document.querySelector(parent) && document.querySelector(child)){
5613								
5614								let dynamicWrap = document.querySelector(parent);
5615								let dynamicTitle = dynamicWrap.querySelector(child);
5616								let dynamicTitleFontSize = parseFloat(getComputedStyle(dynamicTitle).fontSize);
5617								let dynamicTitleFontSizeVW = (dynamicTitleFontSize / window.innerWidth) * 100;
5618							
5619								let dynamicTitleMInSize = 3.2;
5620								let dynamicTitleMaxSize = 55;
5621								
5622								function isMobile() {
5623									return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(navigator.userAgent) || window.matchMedia("(max-width: 768px)").matches;
5624								}
5625								
5626								if (isMobile()) {
5627									dynamicTitleMInSize = 4.2;
5628								} else {
5629									
5630									if(dynamicWrap.classList.contains('lpc-full-width-init')){
5631										dynamicTitleMInSize = 3.2;
5632									} else {
5633										dynamicTitleMInSize = 2;
5634									}
5635								}
5636								
5637								
5638								if (dynamicWrap.classList.contains('lpc-full-width-init')) {
5639									let dynamicBlockWrap = dynamicWrap.closest('.lpc-full-width');
5640									let dynamicBlockIn = dynamicWrap.closest('.lpc-elements-dynamic-headline__wrap');				
5641									let viewportWidth = $(window).width();
5642									let dynamicWrapMargin = (viewportWidth - dynamicBlockWrap.offsetWidth) / 2;
5643		
5644									$(dynamicBlockIn).css({
5645										'margin-left': '-' + (dynamicWrapMargin) + 'px',
5646										'margin-right': '-' + (dynamicWrapMargin) + 'px'
5647									});
5648								}
5649								
5650								
5651								if(dynamicWrap.offsetWidth > dynamicTitle.offsetWidth){
5652									while (dynamicWrap.offsetWidth > dynamicTitle.offsetWidth) {
5653										dynamicTitleFontSizeVW = dynamicTitleFontSizeVW + 0.05;
5654										dynamicTitle.style.fontSize = dynamicTitleFontSizeVW + 'vw';
5655										if(dynamicTitleFontSizeVW >= dynamicTitleMaxSize){
5656											break;
5657										}
5658									}
5659									
5660									dynamicTitle.style.fontSize = (dynamicTitleFontSizeVW - 0.05) + 'vw';			
5661									dynamicTitle.style.opacity = 1;
5662									
5663									if(dynamicTitleFontSizeVW <= dynamicTitleMInSize){
5664										dynamicTitle.style.fontSize = dynamicTitleMInSize + 'vw';
5665									}
5666									
5667									return;
5668								}
5669								
5670								if(dynamicWrap.offsetWidth <= dynamicTitle.offsetWidth){
5671								
5672									while(dynamicWrap.offsetWidth <= dynamicTitle.offsetWidth) {
5673										dynamicTitleFontSizeVW = dynamicTitleFontSizeVW - 0.05;
5674										
5675										dynamicTitle.style.fontSize = dynamicTitleFontSizeVW + 'vw';
5676										
5677										
5678										if(dynamicTitleFontSizeVW <= dynamicTitleMInSize){
5679											break;
5680										}
5681									}
5682									dynamicTitle.style.opacity = 1;
5683									
5684									if(dynamicTitleFontSizeVW <= dynamicTitleMInSize){
5685										dynamicTitle.style.fontSize = dynamicTitleMInSize + 'vw';
5686									}
5687									
5688									return;
5689								}
5690								
5691								dynamicTitle.style.opacity = 1;
5692								
5693								return;
5694							}
5695						}
5696						
5697					}
5698	
5699	
5700	
5701	
5702					if (s3LP.is_cms) {
5703						if (document.querySelector(`${$titleInit} .lpc-elements-dynamic-headline__title`)) {
5704	
5705							document.addEventListener('lpcLoadingDone', function () {
5706								setTimeout(function () {
5707									dynamicTextWidth($titleInit, $title);
5708	
5709									if (document.querySelector($title) && document.querySelector($title).classList.contains('bg_clip')) {
5710										dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5711									}
5712	
5713								}, 1000);
5714	
5715								function waitForStylesheet(callback, delay = 500) {
5716									const interval = setInterval(() => {
5717										if (document.getElementById('lpc-stylesheet')) {
5718											clearInterval(interval);
5719											setTimeout(callback, delay);
5720										}
5721									}, 250);
5722								}
5723	
5724								waitForStylesheet(() => {
5725									dynamicTextWidth($titleInit, $title);
5726								}, 500);
5727							});
5728	
5729							// Watch bg and overlay style changes
5730							if (document.querySelector($title) && document.querySelector($title).classList.contains('bg_clip')) {
5731								let elementBg = document.querySelector($bgItem);
5732								let elementOverlay = document.querySelector($overlayItem);
5733	
5734								let observerBg = new MutationObserver((mutationsList) => {
5735									mutationsList.forEach((mutation) => {
5736										if (mutation.type === "attributes" && mutation.attributeName === "style") {
5737											dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5738										}
5739									});
5740								});
5741	
5742								let config = {
5743									attributes: true,
5744									attributeFilter: ["style"]
5745								};
5746	
5747								observerBg.observe(elementBg, config);
5748								observerBg.observe(elementOverlay, config);
5749							}
5750	
5751							// Watch text content changes
5752							let contentTitle = document.querySelector($title);
5753	
5754							let observerTitle = new MutationObserver((mutations) => {
5755								mutations.forEach((mutation) => {
5756									dynamicTextWidth($titleInit, $title);
5757								});
5758							});
5759	
5760							observerTitle.observe(contentTitle, {
5761								childList: true,
5762								subtree: true,
5763								characterData: true
5764							});
5765	
5766							// On style removed (eraser)
5767							function observeStyleChanges(targetSelector, dynamicFunction) {
5768								let targetTitle = document.querySelector(targetSelector);
5769	
5770								if (!targetTitle) return;
5771	
5772								const observerBlock = new MutationObserver((mutationsList) => {
5773									for (const mutation of mutationsList) {
5774										if (mutation.type === "attributes" && mutation.attributeName === "style") {
5775											if (!targetTitle.getAttribute("style")) {
5776												dynamicFunction();
5777											}
5778										}
5779									}
5780								});
5781	
5782								observerBlock.observe(targetTitle, {
5783									attributes: true,
5784									attributeFilter: ["style"]
5785								});
5786	
5787								dynamicFunction();
5788							}
5789	
5790							observeStyleChanges(
5791								$title,
5792								() => dynamicTextWidth($titleInit, $title)
5793							);
5794	
5795							// On publish
5796							const targetElement = document.querySelector($title);
5797	
5798							if (targetElement) {
5799								const observer = new MutationObserver((mutationsList) => {
5800									mutationsList.forEach((mutation) => {
5801										if (mutation.type === "attributes" && mutation.attributeName === "class") {
5802											if (!targetElement.classList.contains("modified")) {
5803												setTimeout(function () {
5804													dynamicTextWidth($titleInit, $title);
5805	
5806													if (document.querySelector($title) && document.querySelector($title).classList.contains('bg_clip')) {
5807														dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5808													}
5809												}, 200);
5810											}
5811										}
5812									});
5813								});
5814								observer.observe(targetElement, { attributes: true });
5815							}
5816						}
5817	
5818					} else {
5819	
5820						function observeElementWithClass(targetClass) {
5821							let widthTitleObserver = new MutationObserver((mutationsList, observer) => {
5822								let targetElement = document.querySelector('.' + targetClass);
5823								if (targetElement) {
5824									if (document.querySelector(`${$titleInit} .lpc-elements-dynamic-headline__title`)) {
5825										setTimeout(function () {
5826											dynamicTextWidth($titleInit, $title);
5827										}, 500);
5828	
5829										let currentWidth = window.innerWidth;
5830	
5831										window.addEventListener('resize', function () {
5832											if (window.innerWidth !== currentWidth) {
5833												currentWidth = window.innerWidth;
5834	
5835												setTimeout(function () {
5836													dynamicTextWidth($titleInit, $title);
5837												}, 500);
5838											}
5839										}, true);
5840									}
5841	
5842									observer.disconnect();
5843								}
5844							});
5845	
5846							widthTitleObserver.observe(document.body, { childList: true, subtree: true });
5847						}
5848	
5849						observeElementWithClass('lpc-content-wrapper');
5850	
5851						document.addEventListener('DOMContentLoaded', function () {
5852							let dynamic = setInterval(function () {
5853								dynamicTextWidth($titleInit, $title);
5854								clearInterval(dynamic);
5855							}, 1000);
5856	
5857							if (document.querySelector($title) && document.querySelector($title).classList.contains('bg_clip')) {
5858								dynamicTextBg($titleInit, $title, $bgItem, $overlayItem);
5859							}
5860						});
5861					}			
5862				});
5863			}
5864		//}
5865	};*/
5866	
5867	
5868	lpc_template.queue.fullWidthS3 = function ($self) {
5869
5870	    const fullWidth = function() {
5871	        const $blocks = $self.find('.lpc-full-width-init');
5872	        if (!$blocks.length) return;
5873	
5874	        $blocks.each(function() {
5875	            const $block = $(this);
5876	            const $wrap = $block.closest('.lpc-full-width');
5877	            if (!$wrap.length) return;
5878	           
5879	            const blockOffsetLeft = $wrap.offset().left;
5880	            const blockWidth = $wrap.outerWidth();
5881	            const windowWidth = $(window).width();
5882	
5883	            const marginL = Math.max(0, blockOffsetLeft);
5884	            const marginR = Math.max(0, windowWidth - (blockOffsetLeft + blockWidth));
5885	
5886	            $block.css({
5887	                marginLeft: -marginL + "px",
5888	                marginRight: -marginR + "px"
5889	            });
5890	            
5891	            $block.find('.lpc-full-width-content').css({
5892	                maxWidth: blockWidth + "px",
5893	                margin: "0 auto"
5894	            });
5895	            
5896	            $block.find('.lpc-full-width-splide-arrow').css({
5897	                maxWidth: blockWidth + "px",
5898	                margin: "0 auto"
5899	            });
5900	        });
5901	    };
5902	  
5903	    if (typeof s3LP !== "undefined" && s3LP.is_cms) {
5904	        setTimeout(fullWidth, 2000);
5905	    }
5906	};
5907
5908	lpc_template.queue.ImageParallax = function ($self) {
5909
5910		let $blocks = $self.find('.init-image-parallax');
5911		if (!$blocks.length) return;
5912	
5913		$blocks.each(function () {
5914	
5915			const $block = $(this);
5916			const image = $block.find('.lpc-promotions-new__image')[0];
5917			if (!image || isMobile) return;
5918			
5919			const promotion = $block.closest('.lpc-promotions-new')[0];
5920			if (!promotion) return;
5921	
5922			let targetX = 0, targetY = 0;
5923			let currentX = 0, currentY = 0;
5924			let frame = null;
5925	
5926			const intensity = 25;
5927	
5928			const animate = () => {
5929				currentX += (targetX - currentX) * 0.1;
5930				currentY += (targetY - currentY) * 0.1;
5931	
5932				image.style.transform = `translate(${currentX}px, ${currentY}px)`;
5933	
5934				if (Math.abs(currentX - targetX) > 0.1 || Math.abs(currentY - targetY) > 0.1) {
5935					frame = requestAnimationFrame(animate);
5936				} else {
5937					frame = null;
5938				}
5939			};
5940	
5941			promotion.addEventListener('mousemove', (e) => {
5942				const rect = promotion.getBoundingClientRect();
5943				const x = e.clientX - rect.left;
5944				const y = e.clientY - rect.top;
5945	
5946				const offsetX = (x / rect.width - 0.1) * 1;
5947				const offsetY = (y / rect.height - 0.1) * 1;
5948	
5949				targetX = offsetX * intensity;
5950				targetY = offsetY * intensity;
5951	
5952				if (!frame) frame = requestAnimationFrame(animate);
5953			});
5954	
5955			promotion.addEventListener('mouseleave', () => {
5956				targetX = 0;
5957				targetY = 0;
5958				if (!frame) frame = requestAnimationFrame(animate);
5959			});
5960		});
5961	};
5962	
5963	lpc_template.queue.spoilerText = function ($self) {
5964		if (typeof ReactLPConstructor !== 'undefined') {
5965			return;
5966		}
5967		
5968		let $block = $self.find('.lpc-spoiler-text-init');
5969	
5970		if ($block.length) {
5971			$block.each(function () {
5972				let $this = $(this);
5973				let $item = $this.find('.lpc-spoiler-text-item');
5974	
5975				if ($item.length != 0) {
5976					$item.each(function () {
5977						let $title = $(this).find('.lpc-spoiler-title-click');
5978						let $text = $(this).find('.lpc-spoiler-text-hide');
5979						let $button = $(this).find('.lpc-spoiler-more');
5980	
5981						let hideText = document.querySelector('html').getAttribute('lang') === 'ru' ? 'Свернуть' : 'Collapse';
5982						let currentText = document.querySelector('html').getAttribute('lang') === 'ru' ? 'Читать полностью' : 'Read completely';
5983	
5984						let originalText = $text.html().trim(); // Используем .html() вместо .text() чтобы сохранить HTML-структуру.
5985						let limit = parseInt($text.attr('data-limit'), 10);
5986	
5987						if (isNaN(limit)) {
5988							limit = 200;
5989						}
5990	
5991						function expandText() {
5992							$text.html(originalText);
5993							$button.text(hideText).show();
5994						}
5995						
5996	
5997						function collapseText() {
5998							let trimmedText = originalText.substr(0, limit);
5999							$text.html(trimmedText + '...');
6000							$button.text(currentText).hide();
6001							$block.addClass('is-active');
6002						}
6003	
6004						function toggleText() {
6005							if ($text.html() === originalText) {
6006								collapseText();
6007							} else {
6008								expandText();
6009							}
6010						}
6011
6012
6013						if (limit === 0) {
6014							console.log(1);
6015							expandText();
6016							$button.hide();
6017							$title.off('click').removeClass('lpc-spoiler-title-click');
6018						} else if (originalText.length > limit) {
6019							console.log(2);
6020							collapseText();
6021							$title.click(function () {
6022								expandText();
6023							});
6024						} else if (limit > originalText.length) {
6025							console.log(3);
6026							expandText();
6027							$button.hide();
6028							$title.off('click');
6029							$block.addClass('is-active');
6030						} else {
6031							console.log(4);
6032							$button.hide();
6033							$title.off('click');
6034						}
6035						
6036	
6037						$button.click(function () {
6038							collapseText();
6039						});
6040					});
6041				}
6042			});
6043		}
6044	};
6045	
6046	lpc_template.queue.scrollImages = function ($self) {
6047
6048		const $blocks = $self.find('.lpc-scroll-init');
6049		if (!$blocks.length) return;
6050	
6051		$blocks.each(function () {
6052	
6053			const $block = $(this);
6054			const $items = $block.find('.lpc-fixed-images__scroll-item');
6055			const $container = $block.find('.lpc-fixed-images__scroll-image');
6056	
6057			if (!$items.length || !$container.length) return;
6058			
6059			
6060			function setItemsMinHeight() {
6061				const imgHeight = $container.outerHeight();
6062				if (!imgHeight) return;
6063	
6064				$items.css('min-height', imgHeight);
6065			}
6066			
6067			setItemsMinHeight();
6068			
6069			$container.find('img').on('load', setItemsMinHeight);
6070			
6071			let resizeTimer;
6072			window.addEventListener('resize', () => {
6073				clearTimeout(resizeTimer);
6074				resizeTimer = setTimeout(setItemsMinHeight, 100);
6075			});
6076			
6077	
6078			let $activeImg = $container.find('img').first();
6079			let currentSrc = $activeImg.data('src') || $activeImg.attr('src');
6080	
6081			$activeImg.addClass('is-active');
6082	
6083			let ticking = false;
6084	
6085			function checkPosition() {
6086				if (ticking) return;
6087				ticking = true;
6088	
6089				requestAnimationFrame(() => {
6090	
6091					const imgRect = $container[0].getBoundingClientRect();
6092				
6093					const zoneTop = imgRect.top + imgRect.height * 0.15;
6094					const zoneBottom = imgRect.bottom - imgRect.height * 0.15;
6095	
6096					$items.each(function () {
6097						const itemRect = this.getBoundingClientRect();
6098						const itemCenter = itemRect.top + itemRect.height / 2;
6099	
6100						if (itemCenter >= zoneTop && itemCenter <= zoneBottom) {
6101	
6102							const img = this.querySelector('.lpc-fixed-images__image img');
6103							if (!img) return;
6104	
6105							const newSrc = img.dataset.src || img.src;
6106							if (!newSrc || newSrc === currentSrc) return;
6107	
6108							currentSrc = newSrc;
6109	
6110							const nextImg = new Image();
6111							nextImg.src = newSrc;
6112							nextImg.className = 'is-next';
6113	
6114							nextImg.onload = () => {
6115								$container.append(nextImg);
6116	
6117								requestAnimationFrame(() => {
6118									nextImg.classList.add('is-active');
6119									$activeImg.removeClass('is-active');
6120	
6121									setTimeout(() => {
6122										$activeImg.remove();
6123										$activeImg = $(nextImg);
6124									}, 500);
6125								});
6126							};
6127	
6128							return false;
6129						}
6130					});
6131	
6132					ticking = false;
6133				});
6134			}
6135	
6136			window.addEventListener('scroll', checkPosition, { passive: true });
6137			window.addEventListener('resize', checkPosition);
6138	
6139			checkPosition();
6140	
6141		});
6142	};
6143
6144	lpc_template.queue.aroundMagic = function ($self) {
6145		const $animation = $self.find('.lpc-recalculation');
6146		if (!$animation.length) return;
6147	
6148		const items = $animation.find('.lpc-recalculation-title');
6149		if (!items.length) return;
6150	
6151		const observer = new IntersectionObserver((entries, observer) => {
6152			entries.forEach(entry => {
6153				if (!entry.isIntersecting) return;
6154	
6155				const el = entry.target;
6156				const text = el.textContent.trim();
6157				
6158				const match = text.match(/\d[\d\s\u00A0]*/);
6159				if (!match) return;
6160	
6161				const rawNumber = match[0];
6162				
6163				const finalNumber = parseInt(rawNumber.replace(/[\s\u00A0]/g, ''), 10);
6164				if (isNaN(finalNumber)) return;
6165	
6166				if (el.dataset.animated) return;
6167				el.dataset.animated = "true";
6168	
6169				let current = 0;
6170				const duration = 1500;
6171				const fps = 60;
6172				const totalFrames = Math.round(duration / (1000 / fps));
6173				let frame = 0;
6174	
6175				const counter = setInterval(() => {
6176					frame++;
6177					current = Math.round((frame / totalFrames) * finalNumber);
6178				
6179					const formatted = current.toLocaleString('ru-RU');
6180					el.textContent = text.replace(rawNumber, formatted);
6181	
6182					if (frame >= totalFrames) {
6183						el.textContent = text.replace(
6184							rawNumber,
6185							finalNumber.toLocaleString('ru-RU')
6186						);
6187						clearInterval(counter);
6188					}
6189				}, 1000 / fps);
6190	
6191				observer.unobserve(el);
6192			});
6193		}, { threshold: 0.3 });
6194	
6195		items.each(function () {
6196			observer.observe(this);
6197		});
6198	};
6199	
6200	lpc_template.queue.stepArrowPositioning = function ($self) {
6201
6202		const $blocks = $self.find('.init-arrow-positioning');
6203		if (!$blocks.length) return;
6204
6205		function updateStepsArrows($block) {
6206
6207			const mediaSource = $('.decor-wrap').attr('data-media-source');
6208			const $arrows = $block.find('.lpc-steps-new__arrow');
6209		
6210			if (!['media-xl', 'media-lg', 'media-md'].includes(mediaSource)) {
6211				$arrows.css({
6212					top: '',
6213					marginLeft: ''
6214				});
6215				return;
6216			}
6217
6218			const $items = $block.find('.lpc-steps-new__item');
6219
6220			$items.each(function (index) {
6221
6222				const $item  = $(this);
6223				const $arrow = $item.find('.lpc-steps-new__arrow');
6224				const $icon  = $item.find('.lpc-steps-new__icon-box');
6225
6226				if (!$arrow.length || !$icon.length) return;
6227
6228				const $nextItem = $items.eq(index + 1);
6229				if (!$nextItem.length) return;
6230
6231				const itemRect     = $item[0].getBoundingClientRect();
6232				const nextItemRect = $nextItem[0].getBoundingClientRect();
6233				const iconRect     = $icon[0].getBoundingClientRect();
6234				const arrowRect    = $arrow[0].getBoundingClientRect();
6235
6236				const top = (iconRect.top - itemRect.top) + (iconRect.height / 2) - (arrowRect.height / 2);
6237
6238				const centerBetween = (itemRect.right + nextItemRect.left) / 2;
6239
6240				const marginLeft = centerBetween - itemRect.left - (arrowRect.width / 2);
6241
6242				$arrow.css({
6243					top,
6244					marginLeft
6245				});
6246			});
6247		}
6248
6249		$blocks.each(function () {
6250
6251			const $block = $(this);
6252
6253			const run = () => updateStepsArrows($block);
6254
6255			if (typeof s3LP !== 'undefined' && s3LP.is_cms) {
6256				setTimeout(run, 250);
6257			} else {
6258				run();
6259			}
6260			
6261			$(window).on('resize', run);
6262		});
6263	};
6264	
6265	lpc_template.queue.accordeon = function ($self) {
6266	    var $block = $self.find('.lpc-accordion');
6267	
6268	    $block.each(function () {
6269	        let $this = $(this);
6270	        let $accordionItem = $this.find('.lpc-accordion-item');
6271	        let $accordionHeader = $this.find('.lpc-accordion-header');
6272	        let $accordionItemWrap = $this.find('.lpc-accordion-cards__item');
6273	        
6274	        $accordionItemWrap.click(function(event){
6275        		if (!$(event.target).closest($accordionHeader).length && !$(event.target).closest('.lpc-accordion-content').length){
6276        			//!$(this).hasClass("active") && 
6277        			$(this).find(".lpc-accordion-header").trigger("click");
6278        		}
6279	        });
6280	
6281	        function setCookie(name, value, days) {
6282	            let expires = "";
6283	            if (days) {
6284	                let date = new Date();
6285	                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
6286	                expires = "; expires=" + date.toUTCString();
6287	            }
6288	            document.cookie = name + "=" + value + expires + "; path=/";
6289	        }
6290	
6291	        function getCookie(name) {
6292	            let nameEQ = name + "=";
6293	            let ca = document.cookie.split(';');
6294	            for (let i = 0; i < ca.length; i++) {
6295	                let c = ca[i];
6296	                while (c.charAt(0) === ' ') c = c.substring(1, c.length);
6297	                if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
6298	            }
6299	            return null;
6300	        }
6301	
6302	        // функция инициализации карты
6303	        function initMap($map) {
6304	            if ($map.length && !$map.hasClass('initialized')) {
6305	                $map.addClass('initialized'); // ставим сразу
6306	                setTimeout(function () {
6307	                    lpc_template.checkMapInitialization($map);
6308	                }, 400);
6309	            }
6310	        }
6311	
6312	        if (!s3LP.is_cms && $('.lpc-accordeon-manager').length) {
6313	            let activeTabs = getCookie("activeTabs");
6314	            if (activeTabs && activeTabs.length > 0) {
6315	                activeTabs = activeTabs.split(',').filter(index => !isNaN(index));
6316	                activeTabs.forEach(index => {
6317	                    let item = $accordionItem.eq(parseInt(index));
6318	                    if (item.length) {
6319	                        item.addClass('active');
6320	                        item.find('.lpc-accordion-content').show();
6321	                        initMap(item.find('.js-lpc-simple-map').first());
6322	                    }
6323	                });
6324	            } else {
6325	                $accordionItem.each(function () {
6326	                    if ($(this).data('accordeon-opened')) {
6327	                        $(this).addClass('active');
6328	                        $(this).find('.lpc-accordion-content').show();
6329	                        initMap($(this).find('.js-lpc-simple-map').first());
6330	                    }
6331	                });
6332	            }
6333	        } else {
6334	            $accordionItem.each(function () {
6335	                if ($(this).data('accordeon-opened')) {
6336	                    $(this).addClass('active');
6337	                    $(this).find('.lpc-accordion-content').show();
6338	                    initMap($(this).find('.js-lpc-simple-map').first());
6339	                }
6340	            });
6341	        }
6342	        
6343	        
6344	        $accordionHeader.click(function () {
6345	            let parent = $(this).closest('.lpc-accordion-item');
6346	            let $map = parent.find('.js-lpc-simple-map').first();
6347	            let $accordionToggle = $this.closest('.lpc-accordion-toggle');
6348	            
6349	            if($accordionToggle && !parent.hasClass('active')) {			
6350					$accordionToggle.find('.lpc-accordion-item.active .lpc-accordion-content').hide();
6351					$accordionToggle.find('.lpc-accordion-item.active').removeClass('active');					
6352				}
6353	
6354	            parent.toggleClass('active');
6355	            parent.find('.lpc-accordion-content').toggle();
6356	
6357	            initMap($map);
6358	
6359	            if (!s3LP.is_cms && $('.lpc-accordeon-manager').length) {
6360	                let activeItems = [];
6361	                $accordionItem.each(function (index) {
6362	                    if ($(this).hasClass('active')) {
6363	                        activeItems.push(index);
6364	                    }
6365	                });
6366	                setCookie("activeTabs", activeItems.join(','), 7);
6367	            }
6368	        });
6369	        
6370	        
6371	       /* if($this.find('.lpc-elements-list-3__item').length!=0) {
6372				$this.find('.lpc-elements-list-3__item').each(function(){
6373					let appendItem = $this.find('.lpc-elements-list-3__title');
6374					$this.find('.lpc-elements-list-3__icon').appendTo(appendItem);
6375				});
6376			}*/
6377	        
6378	        
6379	    });
6380	};
6381	
6382	lpc_template.queue.cmsFormGlobalStyles = function($self) {
6383		function observeIframe() {
6384			let iframe = document.querySelector('.lp-panel-iframe') || document.querySelector('._frame_4flwn_1');
6385
6386			if (!iframe || !iframe.contentWindow || !iframe.contentDocument) {
6387				return;
6388			}
6389			
6390			let iframeDoc = iframe.contentDocument || iframe.contentWindow.document; // Доступ к контенту iframe
6391			
6392			$(iframeDoc).find('[data-element-alias=".lpc-block .lp-form-tpl__field-text"]').addClass('lp-form-tpl__field-text');
6393		}
6394		$('._live__settings-list li:first a').on('click', function() {
6395			setTimeout(function() {
6396				observeIframe();
6397			}, 3200);
6398		});
6399	};
6400	
6401	lpc_template.queue.lpcTamlim = function ($self) {
6402	    var $block = $self.find(".lpc-tamlim-init");
6403	
6404	    if (!$block.length) return;
6405	
6406	    $block.each(function () {
6407	        let $this = $(this);
6408	        let items = $this.find('.lpc-tamlim__item');
6409	
6410	        items.each(function (i) {
6411	            let current = items[i];
6412	            let next = items[i + 1];
6413	
6414	            if (next && next.classList.contains('_flag_title')) {
6415	                current.classList.add('_before_flag');
6416	            }
6417	        });
6418	    });
6419	};
6420
6421	lpc_template.queue.lpcSimpleAccordeon = function ($self) {
6422		var $block = $self.find(".js_accordeon_title"),
6423			activeClass = "active";
6424	
6425		if ($block.length) {
6426			$block.on("click", function (e) {
6427				e.preventDefault();
6428	
6429				var $this = $(this),
6430					$ymap = $this
6431						.closest("[data-block-layout]")
6432						.find(".js-lpc-simple-map");
6433				($thisParent = $this.closest("._parent")),
6434					($thisBody = $thisParent.find("._content"));
6435	
6436				if ($thisParent.hasClass(activeClass)) {
6437					$thisBody.slideUp(400, function () {
6438						$thisParent.removeClass(activeClass);
6439						if ($ymap.length && $ymap.data("ymaps")) {
6440							$ymap.data("ymaps").container.fitToViewport();
6441						}
6442					});
6443				} else {
6444					$thisBody.slideDown(400, function () {
6445						$thisParent.addClass(activeClass);
6446						if ($ymap.length && $ymap.data("ymaps")) {
6447							$ymap.data("ymaps").container.fitToViewport();
6448						}
6449					});
6450				}
6451			});
6452		}
6453	};
6454
6455	lpc_template.queue.lpcSimpleColumn = function ($self) {
6456		var $block = $self.find(".js-lpc-simple-colum");
6457	
6458		if ($block.length) {
6459			$block.each(function () {
6460				var $this = $(this),
6461					$items = $this.find("._parent");
6462				countArray = $this.data("column-count");
6463	
6464				$doc.on("checkDeviceType", function (e, param) {
6465					var thisCount =
6466						param === "mobile"
6467							? countArray[2]
6468							: param === "tablet"
6469								? countArray[1]
6470								: countArray[0];
6471	
6472					unwrap($items);
6473	
6474					if (thisCount == 1) {
6475						$items.wrap('<div class="_simple-col"></div>');
6476						return;
6477					}
6478	
6479					var itemsLengthInColumn = Math.round($items.length / thisCount);
6480	
6481					for (let i = 1; i < thisCount + 1; i += 1) {
6482						$items
6483							.filter(function (index) {
6484								return (
6485									index >= (i - 1) * itemsLengthInColumn &&
6486									index < i * itemsLengthInColumn
6487								);
6488							})
6489							.wrapAll('<div class="_simple-col"></div>');
6490					}
6491				});
6492			});
6493	
6494			function unwrap($list) {
6495				$list.each(function () {
6496					if (!this.parentNode.classList.contains("_simple-col")) return;
6497					$(this).unwrap();
6498				});
6499			}
6500		}
6501	};
6502	
6503	lpc_template.queue.blockAfterBefore = function ($self) {
6504		var $block = $self.find(".lpc-before-and-after-init");
6505	
6506		if ($block.length) {
6507			(() => {'use strict';
6508	
6509				class BeforeAfter {
6510					constructor(selector = '.before-after') {
6511						this.selector = selector;
6512						this.items = [];
6513					}
6514	
6515					init() {
6516						let wrappers = document.querySelectorAll(this.selector);
6517	
6518						for (let wrapper of wrappers) {
6519							if (wrapper.dataset.beforeAfterInitialized === 'true') {
6520								continue;
6521							}
6522							let item = new BeforeAfterItem(wrapper).init();
6523							this.items.push(item);
6524							
6525							wrapper.dataset.beforeAfterInitialized = 'true';
6526							
6527							let observer = new MutationObserver(function (mutations) {
6528								mutations.forEach(function (mutation) {
6529									if ($(mutation.target).hasClass('lp-selected-element')) {
6530										$(mutation.target).parent().addClass('active');
6531									} else {
6532										$(mutation.target).parent().removeClass('active');
6533									}
6534								});
6535							});
6536							let config = {
6537								attributes: true,
6538								attributeFilter: ['class']
6539							};
6540							
6541							observer.observe($(wrapper).find('.before-after__img-before')[0], config);
6542							observer.observe($(wrapper).find('.before-after__img-after')[0], config);
6543						}
6544					}
6545				}
6546	
6547				class BeforeAfterItem {
6548					constructor(el) {
6549						this.wrapper = el;
6550						this.dragElWrapper = null;
6551						this.viewport = null;
6552						this.before = null;
6553						this.after = null;
6554						this.offset = 0;
6555						this.pageXStart = 0;
6556						this.startOffset = 0;
6557						this.onPointerDown = this.onPointerDown.bind(this);
6558						this.onPointerMove = this.onPointerMove.bind(this);
6559						this.onPointerUp = this.onPointerUp.bind(this);
6560					}
6561					init() {
6562						let wrapper = this.wrapper;
6563	
6564						let dragElWrapper = this.dragElWrapper = document.createElement('div');
6565	
6566						dragElWrapper.classList.add('before-after__drag-wrapper');
6567						dragElWrapper.style.left = '50%';
6568	
6569						let dragEl = document.createElement('div');
6570	
6571						dragEl.classList.add('before-after__drag');
6572	
6573						dragElWrapper.append(dragEl);
6574	
6575						let viewport = this.viewport = wrapper.querySelector('.before-after__viewport');
6576	
6577						viewport.append(dragElWrapper);
6578						wrapper.classList.add('before-after--loaded');
6579	
6580						this.before = viewport.querySelector('.lpc-image-before');
6581						this.after = viewport.querySelector('.lpc-image-after');
6582	
6583						this.move(this.offset);
6584	
6585						dragElWrapper.addEventListener('mousedown', this.onPointerDown);
6586						dragElWrapper.addEventListener('touchstart', this.onPointerDown);
6587	
6588						dragElWrapper.addEventListener('dragstart', () => {
6589							return false;
6590						});
6591	
6592						return this;
6593					}
6594	
6595					onPointerDown(e) {
6596						e.stopPropagation();
6597	
6598						if (e.touches) {
6599							this.pageXStart = e.touches[0].pageX;
6600						} else {
6601							this.pageXStart = e.pageX;
6602						}
6603						this.startOffset = this.offset;
6604	
6605						document.addEventListener('mousemove', this.onPointerMove);
6606						document.addEventListener('touchmove', this.onPointerMove);
6607						document.addEventListener('mouseup', this.onPointerUp);
6608						document.addEventListener('touchend', this.onPointerUp);
6609					}
6610	
6611					onPointerMove(e) {
6612						let viewport = this.viewport,
6613							pxOffset = 0,
6614							percentOffset = 0;
6615	
6616						if (e.touches) {
6617							pxOffset = e.touches[0].pageX - this.pageXStart;
6618						} else {
6619							pxOffset = e.pageX - this.pageXStart;
6620						}
6621	
6622						percentOffset = parseFloat((pxOffset / viewport.clientWidth * 100).toFixed(6));
6623	
6624						this.offset = this.startOffset + percentOffset;
6625	
6626						if (this.offset >= 50) {
6627							this.offset = 50;
6628						} else if (this.offset <= -50) {
6629							this.offset = -50;
6630						}
6631	
6632						this.move(this.offset);
6633					}
6634	
6635					onPointerUp() {
6636						document.removeEventListener('mousemove', this.onPointerMove);
6637						document.removeEventListener('touchmove', this.onPointerMove);
6638						document.removeEventListener('mouseup', this.onPointerUp);
6639						document.removeEventListener('touchend', this.onPointerUp);
6640					}
6641	
6642					move(offset) {
6643						this.dragElWrapper.style.left = 'calc(50% + ' + offset + '%)';
6644						this.before.style.clipPath = 'inset(0 calc(50% - ' + offset + '%) 0 0)';
6645						this.after.style.clipPath = 'inset(0 0 0 calc(50% + ' + offset + '%))';
6646					}
6647	
6648				}
6649				window.BeforeAfter = BeforeAfter;
6650			})();
6651	
6652			new BeforeAfter().init();
6653		}
6654	};
6655	
6656	lpc_template.queue.spoilerBlock = function ($self) {
6657	    let $block = $self.hasClass('spoiler-init') ? $self : $self.find('.spoiler-init');
6658
6659		$block.each(function(){
6660			let $this = $(this);
6661
6662			initSpoiler();
6663			document.addEventListener('dataMediaSourceChange', initSpoiler);
6664			
6665			function initSpoiler() {
6666				let $hidden = $this.find('.spoiler-item:hidden');
6667				let $firstNotHidden = $this.find('.spoiler-item').first();
6668				let $btn = $this.find('.spoiler-btn');
6669				let $btnWrap = $this.find('.spoiler-btn-wrap');
6670
6671
6672				if ($hidden.length) {
6673					$btnWrap.addClass('show_spoiler');
6674					
6675					$btn.on('click', function(){
6676						$hidden.slideDown('150', function(){
6677							if ($firstNotHidden.css('display') == 'flex') {
6678								$hidden.css('display', 'flex');
6679							}
6680						});
6681						$(this).hide();
6682					});
6683				} else  {
6684					$btnWrap.removeClass('show_spoiler');
6685				}
6686			}
6687		});
6688	};
6689	
6690	lpc_template.queue.iframeLazyLoading = function($self) {
6691		var $block = $self.find('.lpc-lazy-iframe-js');
6692		var iframes = $block.find($('iframe'));
6693		
6694		if($block.length && iframes.length) {
6695		  iframes.each(function() {
6696		      var iframe = $(this);
6697			  /*var src = iframe.attr('src');
6698			  iframe.removeAttr('src');
6699			  iframe.attr('loading', 'lazy');
6700			  iframe.attr('data-src', src);*/
6701		      iframe.addClass('lazy lazyload');
6702		  });
6703		}
6704	};
6705	
6706	lpc_template.queue.lazyLoading = function($self) {
6707		var $block = $self.find('.lpc-lazy-loading-init');
6708	
6709		if ($block.length) {
6710			$block.each(function () {
6711				const $this = $(this);
6712				const blocks = $this.find('.lpc-lazy-loading-item');
6713				const blocksScrollShow = 1;
6714				let visibleBlockCount = blocksScrollShow;
6715	
6716				function showBlocks(startIndex, endIndex) {
6717					for (let i = startIndex; i < endIndex; i++) {
6718						blocks.eq(i).removeClass('hidden');
6719					}
6720				}
6721	
6722				function hideAllBlocks() {
6723					blocks.addClass('hidden');
6724				}
6725	
6726				hideAllBlocks();
6727				showBlocks(0, 3);
6728	
6729				function handleScroll() {
6730					const scrollTop = $(window).scrollTop();
6731					const windowHeight = $(window).height();
6732					const totalBlockCount = blocks.length;
6733					const totalVisibleBlocks = Math.min(visibleBlockCount, totalBlockCount);
6734					const lazyLoadingListBottom = $this.find('.lpc-lazy-loading-list').offset().top + $this.find('.lpc-lazy-loading-list').outerHeight() + 100;
6735	
6736					if (scrollTop + windowHeight >= lazyLoadingListBottom) {
6737						if (visibleBlockCount < totalBlockCount) {
6738							const newVisibleCount = Math.min(visibleBlockCount + blocksScrollShow, totalBlockCount);
6739							showBlocks(visibleBlockCount, newVisibleCount);
6740							visibleBlockCount = newVisibleCount;
6741						}
6742					}
6743				}
6744	
6745				$(window).on('scroll', handleScroll);
6746			});
6747		}
6748	};
6749	
6750	lpc_template.queue.typeWriter = function ($self) {
6751		let $block = $self.find('.lpc-typewriter-init');
6752	
6753		if ($block.length) {
6754			$block.each(function () {
6755				const $this = $(this);
6756				const stringElements = $this.find(".lpc-typewriter-string");
6757				const delay = $this.attr("data-delay");
6758				const delayDeletion = $this.attr("data-delay-deletion");
6759				const stopDialing = $this.attr("data-stop-dialing");
6760	
6761				function typeText(element, text, delay, callback) {
6762					let index = 0;
6763					const textLength = text.length;
6764	
6765					function addCharacter() {
6766						if (index < textLength) {
6767							element.textContent += text.charAt(index);
6768							index++;
6769							setTimeout(addCharacter, delay);
6770						} else {
6771							setTimeout(callback, delayDeletion);
6772						}
6773					}
6774	
6775					addCharacter();
6776				}
6777	
6778				function eraseText(element, delay, callback) {
6779					const text = element.textContent;
6780					let index = text.length;
6781	
6782					function removeCharacter() {
6783						if (index > 0) {
6784							element.textContent = text.substring(0, index - 1);
6785							index--;
6786							setTimeout(removeCharacter, delay);
6787						} else {
6788							callback();
6789						}
6790					}
6791	
6792					removeCharacter();
6793				}
6794	
6795				function animateElements(index) {
6796					if (index < stringElements.length) {
6797						const element = stringElements[index];
6798						const text = element.getAttribute("data-text");
6799				
6800						typeText(element, text, delay, function () {
6801							if (index === stringElements.length - 1 && stopDialing === "1") {
6802								
6803								setTimeout(function () {
6804									element.style.display = "inline";
6805									animateElements(index + 1);
6806								}, 250);
6807								
6808							} else {
6809								
6810								eraseText(element, delay, function () {
6811									element.style.display = "none";
6812									setTimeout(function () {
6813										animateElements(index + 1);
6814									}, 250);
6815								});
6816							}
6817						});
6818					} else {
6819						if (stopDialing === "1") {
6820							const lastElement = stringElements[stringElements.length - 1];
6821							const lastText = lastElement.getAttribute("data-text");
6822							lastElement.textContent = lastText;
6823						} else {
6824							setTimeout(function () {
6825								$this.find(".lpc-typewriter-string").each(function () {
6826									$(this).text(""); 
6827									$(this).css("display", "inline");
6828								});
6829								animateElements(0);
6830							}, delay);
6831						}
6832					}
6833				}
6834	
6835				animateElements(0);
6836			});
6837		}
6838	};
6839	
6840	lpc_template.queue.furniturePoints = function ($self) {
6841
6842		let $blocks = $self.find('.furniture-points-init');
6843	
6844		if (!$blocks.length) return;
6845	
6846		$blocks.each(function () {
6847	
6848			const $block  = $(this);
6849			const $items  = $block.find('.lpc-furniture-points__point');
6850			const $image  = $block.find('.lpc-furniture-points__image-box');
6851	
6852			if (!$items.length) return;
6853	
6854			let isDragging = false;
6855			let wasDragging = false;
6856			let $currentItem = null;
6857	
6858			const ns = '.furniturePoints_' + Math.random().toString(36).slice(2);
6859	
6860			function setActive(index) {
6861				$items.removeClass('_active');
6862	
6863				const $item  = $items.eq(index);
6864	
6865				$item.addClass('_active');
6866				
6867			}
6868	
6869			$items.each(function (i) {
6870				$(this).on('click', function (e) {
6871	
6872					if (wasDragging) {
6873						wasDragging = false;
6874						return;
6875					}
6876	
6877					e.preventDefault();
6878					e.stopPropagation();
6879	
6880					setActive(i);
6881				});
6882			});
6883	
6884			$items.each(function (i) {
6885				$(this).on('click', function (e) {
6886					e.preventDefault();
6887					e.stopPropagation();
6888	
6889					setActive(i);
6890				});
6891			});
6892	
6893			$items.each(function (i) {
6894				$(this).on('click', function (e) {
6895	
6896					if ($(e.target).closest('.lpc-furniture-points__point-number').length) return;
6897					if ($(e.target).closest('.lpc-furniture-points__tooltip').length) return;
6898	
6899					setActive(i);
6900				});
6901			});
6902	
6903			/*$items.on('mousedown', function (e) {
6904	
6905				if (!s3LP.is_cms) return;
6906	
6907				isDragging = true;
6908				$currentItem = $(this).closest('.lpc-furniture-points__point');
6909	
6910				e.preventDefault();
6911				e.stopPropagation();
6912			});
6913	
6914			$(document).off('mousemove' + ns).on('mousemove' + ns, function (e) {
6915	
6916				if (!isDragging || !$currentItem || !$image.length) return;
6917	
6918				const rect = $image.get(0).getBoundingClientRect();
6919	
6920				let x = ((e.clientX - rect.left) / rect.width) * 100;
6921				let y = ((e.clientY - rect.top) / rect.height) * 100;
6922	
6923				x = Math.max(0, Math.min(100, x));
6924				y = Math.max(0, Math.min(100, y));
6925	
6926				wasDragging = true;
6927	
6928				const xVal = x.toFixed(2);
6929				const yVal = y.toFixed(2);
6930	
6931				$currentItem.css({
6932					left: xVal + '%',
6933					top: yVal + '%'
6934				});
6935	
6936				updateCoords($currentItem, xVal, yVal);
6937			});
6938	
6939			$(document).off('mouseup' + ns).on('mouseup' + ns, function () {
6940	
6941				isDragging = false;
6942				$currentItem = null;
6943	
6944				setTimeout(function () {
6945					wasDragging = false;
6946				}, 10);
6947			});*/
6948	
6949			function updateCoords($item, x, y) {
6950				const $inputX = $item.find('input[name="point_x"]');
6951				const $inputY = $item.find('input[name="point_y"]');
6952	
6953				if ($inputX.length) {
6954					$inputX.val(x).trigger('change');
6955				}
6956	
6957				if ($inputY.length) {
6958					$inputY.val(y).trigger('change');
6959				}
6960	
6961				const $coords = $item.find('.lpc-furniture-points__point-coords');
6962	
6963				if ($coords.length) {
6964					$coords.html(
6965						'X: ' + x + '%<br>' +
6966						'Y: ' + y + '%'
6967					);
6968				}
6969			}
6970	
6971			setActive(0);
6972	
6973		});
6974	};
6975	
6976	lpc_template.queue.memorialParts = function ($self) {
6977
6978		let $blocks = $self.find('.memorial-parts-init');
6979		
6980		if (!$blocks.length) return;
6981	
6982		$blocks.each(function () {
6983		
6984			const $block  = $(this);
6985			const $points = $block.find('.lpc-memorial-parts__point');
6986			const $items  = $block.find('.lpc-memorial-parts__item');
6987			const $image  = $block.find('.lpc-memorial-parts__visual-box');
6988	
6989			if (!$points.length) return;
6990	
6991			let isDragging = false;
6992			let wasDragging = false;
6993			let $currentPoint = null;
6994	
6995			const ns = '.memorialParts_' + Math.random().toString(36).slice(2);
6996	
6997			function setActive(index){
6998	
6999				$points.removeClass('_active');
7000				$items.removeClass('_active');
7001	
7002				const $point = $points.eq(index);
7003				const $item  = $items.eq(index);
7004	
7005				$point.addClass('_active');
7006				$item.addClass('_active');
7007			}
7008	
7009			$points.each(function(i){
7010	
7011				$(this).on('click', function(){
7012	
7013					if (wasDragging) {
7014						wasDragging = false;
7015						return;
7016					}
7017	
7018					setActive(i);
7019	
7020				});
7021	
7022			});
7023	
7024			$items.each(function(i){
7025	
7026				$(this).on('click', function(){
7027					setActive(i);
7028				});
7029	
7030			});
7031	
7032			/*$points.on('mousedown', function(e){
7033	
7034				if (!s3LP.is_cms) return;
7035	
7036				isDragging = true;
7037				$currentPoint = $(this);
7038	
7039				e.preventDefault();
7040				e.stopPropagation();
7041	
7042			});
7043	
7044			$(document).off('mousemove'+ns).on('mousemove'+ns,function(e){
7045	
7046				if (!isDragging || !$currentPoint) return;
7047	
7048				const rect = $image.get(0).getBoundingClientRect();
7049	
7050				let x = ((e.clientX - rect.left) / rect.width) * 100;
7051				let y = ((e.clientY - rect.top) / rect.height) * 100;
7052	
7053				x = Math.max(0, Math.min(100, x));
7054				y = Math.max(0, Math.min(100, y));
7055	
7056				wasDragging = true;
7057	
7058				const xVal = x.toFixed(2) + '%';
7059				const yVal = y.toFixed(2) + '%';
7060	
7061				$currentPoint.css({
7062					left: xVal,
7063					top:  yVal
7064				});
7065	
7066				updateCoords($currentPoint, xVal, yVal);
7067	
7068			});
7069	
7070			$(document).off('mouseup'+ns).on('mouseup'+ns,function(){
7071	
7072				isDragging = false;
7073				$currentPoint = null;
7074	
7075				setTimeout(function(){
7076					wasDragging = false;
7077				},10);
7078	
7079			});*/
7080	
7081			function updateCoords($point, x, y){
7082				
7083				const $inputX = $point.find('input[name="point_x"]');
7084				const $inputY = $point.find('input[name="point_y"]');
7085			
7086				if ($inputX.length) {
7087					$inputX.val(x);
7088				}
7089			
7090				if ($inputY.length) {
7091					$inputY.val(y);
7092				}
7093	
7094				const $coords = $point.find('.lpc-memorial-parts__point-coords');
7095	
7096				if ($coords.length){
7097					$coords.html(
7098						'X: ' + x + '<br>' +
7099						'Y: ' + y
7100					);
7101				}
7102	
7103			}
7104	
7105			setActive(0);
7106	
7107		});
7108	};
7109	
7110	lpc_template.queue.furniturePoints = function ($self) {
7111
7112		let $blocks = $self.find('.furniture-points-init');
7113	
7114		if (!$blocks.length) return;
7115	
7116		$blocks.each(function () {
7117	
7118			const $block = $(this);
7119	
7120			// ДВЕ ГРУППЫ ТОЧЕК
7121			const $pointsImage = $block.find('.lpc-furniture-points__points._image_points .lpc-furniture-points__point');
7122			const $pointsList  = $block.find('.lpc-furniture-points__points:not(._image_points) .lpc-furniture-points__point');
7123	
7124			const $numbers = $block.find('.lpc-furniture-points__point-number');
7125			const $cards   = $block.find('.lpc-furniture-points__tooltip');
7126			const $image   = $block.find('.lpc-furniture-points__image-box');
7127	
7128			if (!$pointsImage.length && !$pointsList.length) return;
7129	
7130			let isDragging = false;
7131			let wasDragging = false;
7132			let $currentItem = null;
7133	
7134			const ns = '.furniturePoints_' + Math.random().toString(36).slice(2);
7135		
7136			function getConfiguredMode() {
7137				return $block.data('interaction') === 'hover' ? 'hover' : 'click';
7138			}
7139			
7140			function getCurrentMedia() {
7141				const $decorWrap = document.querySelector('.decor-wrap');
7142				return $decorWrap ? $decorWrap.dataset.mediaSource : '';
7143			}
7144	
7145			function getInteractionMode() {
7146				const media = getCurrentMedia();
7147	
7148				if (media === 'media-md' || media === 'media-sm' || media === 'media-xs') {
7149					return 'click';
7150				}
7151	
7152				return getConfiguredMode();
7153			}
7154	
7155			function isMobileMedia() {
7156				const media = getCurrentMedia();
7157				return media === 'media-md' || media === 'media-sm' || media === 'media-xs';
7158			}
7159	
7160			function setActiveById(id) {
7161				$pointsImage.removeClass('_active');
7162				$pointsList.removeClass('_active');
7163				$numbers.removeClass('_active');
7164				$cards.removeClass('_active');
7165	
7166				$pointsImage.filter(`[data-id="${id}"]`).addClass('_active');
7167				$pointsList.filter(`[data-id="${id}"]`).addClass('_active');
7168				$cards.filter(`[data-id="${id}"]`).addClass('_active');
7169	
7170				$numbers.each(function () {
7171					const $point = $(this).closest('.lpc-furniture-points__point');
7172					if ($point.data('id') == id) {
7173						$(this).addClass('_active');
7174					}
7175				});
7176			}
7177	
7178			function scrollToTooltipById(id) {
7179				if (!isMobileMedia()) return;
7180	
7181				const $tooltip = $cards.filter(`[data-id="${id}"]`);
7182				if (!$tooltip.length) return;
7183				
7184				const $scrollContainer = $block.find('.lpc-furniture-points__points');
7185	
7186				if (!$scrollContainer.length) return;
7187	
7188				const container = $scrollContainer.get(0);
7189				const tooltip = $tooltip.get(0);
7190	
7191				const targetLeft =
7192					tooltip.offsetLeft - (container.clientWidth / 2) + (tooltip.clientWidth / 2);
7193	
7194				$scrollContainer.stop().animate({
7195					scrollLeft: Math.max(0, targetLeft)
7196				}, 300);
7197			}
7198	
7199			function activatePoint(id, withScroll = true) {
7200				setActiveById(id);
7201	
7202				if (withScroll) {
7203					scrollToTooltipById(id);
7204				}
7205			}
7206	
7207
7208			$block.on('click', '.lpc-furniture-points__point', function (e) {
7209				if ($(e.target).closest('.lpc-furniture-points__tooltip').length) return;
7210				if ($(e.target).closest('.lpc-furniture-points__point-number').length) return;
7211	
7212				const mode = getInteractionMode();
7213				if (mode !== 'click') return;
7214	
7215				const id = $(this).data('id');
7216				activatePoint(id, true);
7217			});
7218	
7219			
7220			$block.on('click', '.lpc-furniture-points__point-number', function (e) {
7221				if (wasDragging) {
7222					wasDragging = false;
7223					return;
7224				}
7225	
7226				e.preventDefault();
7227				e.stopPropagation();
7228	
7229				const mode = getInteractionMode();
7230				if (mode !== 'click') return;
7231	
7232				const id = $(this).closest('.lpc-furniture-points__point').data('id');
7233				activatePoint(id, true);
7234			});
7235	
7236			
7237			$block.on('click', '.lpc-furniture-points__tooltip', function (e) {
7238				e.preventDefault();
7239				e.stopPropagation();
7240	
7241				const mode = getInteractionMode();
7242				if (mode !== 'click') return;
7243	
7244				const id = $(this).data('id');
7245				activatePoint(id, true);
7246			});
7247	
7248			
7249			$block.on('mouseenter', '.lpc-furniture-points__point, .lpc-furniture-points__tooltip', function () {
7250				const mode = getInteractionMode();
7251				if (mode !== 'hover') return;
7252	
7253				const id = $(this).data('id');
7254				activatePoint(id, false);
7255			});
7256	
7257			$block.on('mouseenter', '.lpc-furniture-points__point-number', function () {
7258				const mode = getInteractionMode();
7259				if (mode !== 'hover') return;
7260	
7261				const id = $(this).closest('.lpc-furniture-points__point').data('id');
7262				activatePoint(id, false);
7263			});
7264	
7265			$block.on('mousedown', '.lpc-furniture-points__point-number', function (e) {
7266				if (!s3LP.is_cms) return;
7267	
7268				isDragging = true;
7269				$currentItem = $(this).closest('.lpc-furniture-points__point');
7270	
7271				e.preventDefault();
7272				e.stopPropagation();
7273			});
7274	
7275			$(document).off('mousemove' + ns).on('mousemove' + ns, function (e) {
7276				if (!isDragging || !$currentItem || !$image.length) return;
7277	
7278				const rect = $image.get(0).getBoundingClientRect();
7279	
7280				let x = ((e.clientX - rect.left) / rect.width) * 100;
7281				let y = ((e.clientY - rect.top) / rect.height) * 100;
7282	
7283				x = Math.max(0, Math.min(100, x));
7284				y = Math.max(0, Math.min(100, y));
7285	
7286				wasDragging = true;
7287	
7288				const xVal = x.toFixed(2);
7289				const yVal = y.toFixed(2);
7290	
7291				const id = $currentItem.data('id');
7292	
7293				$pointsImage.filter(`[data-id="${id}"]`).css({
7294					left: xVal + '%',
7295					top: yVal + '%'
7296				});
7297	
7298				$pointsList.filter(`[data-id="${id}"]`).css({
7299					left: xVal + '%',
7300					top: yVal + '%'
7301				});
7302	
7303				updateCoords($pointsList.filter(`[data-id="${id}"]`), xVal, yVal);
7304			});
7305	
7306			$(document).off('mouseup' + ns).on('mouseup' + ns, function () {
7307				isDragging = false;
7308				$currentItem = null;
7309	
7310				setTimeout(function () {
7311					wasDragging = false;
7312				}, 10);
7313			});
7314	
7315			function updateCoords($item, x, y) {
7316				const $inputX = $item.find('input[name="point_x"]');
7317				const $inputY = $item.find('input[name="point_y"]');
7318	
7319				if ($inputX.length) {
7320					$inputX.val(x).trigger('change');
7321				}
7322	
7323				if ($inputY.length) {
7324					$inputY.val(y).trigger('change');
7325				}
7326	
7327				const $coords = $item.find('.lpc-furniture-points__point-coords');
7328	
7329				if ($coords.length) {
7330					$coords.html(
7331						'X: ' + x + '%<br>' +
7332						'Y: ' + y + '%'
7333					);
7334				}
7335			}
7336	
7337			const firstId = $pointsList.first().data('id');
7338			if (firstId !== undefined) {
7339				activatePoint(firstId, false);
7340			}
7341	
7342			function updateTooltipPosition($tooltip) {
7343				if (!$tooltip.length) return;
7344	
7345				const $container = $block.find('.lpc-furniture-points__image-box');
7346				const wasHidden = !$tooltip.hasClass('_active');
7347	
7348				if (wasHidden) {
7349					$tooltip.css({
7350						display: 'block',
7351						visibility: 'hidden'
7352					});
7353				}
7354	
7355				const tooltipRect = $tooltip.get(0).getBoundingClientRect();
7356				const containerRect = $container.get(0).getBoundingClientRect();
7357	
7358				$tooltip.css({
7359					left: '',
7360					right: ''
7361				});
7362	
7363				if (tooltipRect.right > containerRect.right) {
7364					$tooltip.css({
7365						left: 'auto',
7366						right: 0
7367					});
7368				} else {
7369					$tooltip.css({
7370						left: 0,
7371						right: 'auto'
7372					});
7373				}
7374	
7375				if (wasHidden) {
7376					$tooltip.css({
7377						display: '',
7378						visibility: ''
7379					});
7380				}
7381			}
7382	
7383			if (!s3LP.is_cms) {
7384				$cards.each(function () {
7385					updateTooltipPosition($(this));
7386				});
7387			}
7388	
7389			document.addEventListener('dataMediaSourceChange', function () {
7390				const activeId = $cards.filter('._active').data('id') || $pointsList.first().data('id');
7391				if (activeId !== undefined) {
7392					activatePoint(activeId, false);
7393				}
7394			});
7395		});
7396	};
7397	
7398	lpc_template.queue.albumGallery = function ($self) {
7399	    let $block = $self.find('.lpc-album-gallery-init');
7400	
7401	    if ($block.length) {
7402	        $block.each(function () {
7403	            let $this = $(this);
7404	            let item = $this.find('.lpc-gallery-click');
7405	            let popup = $this.find('.lpc-album-gallery-popup');
7406	            let popupItems = $this.find('.lpc-album-gallery-popup__item');
7407	            let buttonBack = $this.find('.lpc-album-gallery-popup__back');
7408	            let buttonClose = $this.find('.lpc-album-gallery-popup__close');
7409	
7410	            let body = $('body');
7411	            let popupImageBox = popup.find('.lpc-album-gallery-popup__image-box');
7412				let mosaicWrap = $(document).find('.mosaic-wrap');
7413				
7414				setTimeout(function(){
7415					if (mosaicWrap.length && !$block.hasClass('lpc_constructor')) {
7416					    mosaicWrap.prepend(popup);
7417					    popup.addClass('lpc-block');
7418					}
7419				}, 300);
7420	            
7421	            if (popup.find('.js-new-lg-init').length) {
7422	            	
7423	            	popupImageBox.click(function () {
7424		                popup.addClass('is-hidden'); 
7425		            });
7426		
7427		            body.on('click', function (event) {
7428		                if (!$(event.target).closest('.lg-prev, .lg-next, .lg-toolbar, .lg-image, .lpc-album-gallery-popup, .lpc-album-gallery-popup__image-box').length) {
7429		                    popup.removeClass('is-hidden');
7430		                }
7431		                
7432		                if ($(event.target).closest('.lg-close').length) {
7433		                	popup.removeClass('is-hidden');
7434		                } 
7435		            });
7436	            }
7437	
7438	            item.click(function () {
7439	                let dataIndex = $(this).data("index");
7440	
7441	                popup.fadeIn().addClass("active");
7442	
7443	                if (!isMobile) {
7444	                    $("body").css({ 'padding-right': '17px' });
7445	                }
7446	
7447	                $("html").addClass("lpc-no-scroll");
7448	                popupItems.removeClass("active");
7449	                popupItems.filter("[data-index='" + dataIndex + "']").addClass("active");
7450	            });
7451	
7452	            buttonBack.click(function () {
7453	                popup.fadeOut().removeClass("active");
7454	                $("body").css({ 'padding-right': '' });
7455	                $("html").removeClass("lpc-no-scroll"); 
7456	                popupItems.removeClass("active");
7457	            });
7458	
7459	            buttonClose.click(function () {
7460	                popup.fadeOut().removeClass("active");
7461	                $("body").css({ 'padding-right': '' });
7462	                $("html").removeClass("lpc-no-scroll"); 
7463	                popupItems.removeClass("active");
7464	            });
7465	
7466				$(document).keydown(function (e) {
7467					if (e.keyCode === 27 && !$('.lg-outer').length) { 
7468						popup.fadeOut().removeClass("active");
7469						$("body").css({ 'padding-right': '' });
7470						$("html").removeClass("lpc-no-scroll"); 
7471						popupItems.removeClass("active");
7472					}
7473					
7474					popup.removeClass('is-hidden');
7475				});
7476	        });
7477	    }
7478	};
7479	
7480	lpc_template.queue.splideMarquee = function ($self) {
7481		let $block = $self.attr('data-marquee-init') ? $self : $self.find('[data-marquee-init]');
7482	
7483		setTimeout(function(){
7484		
7485			if ($block.length) {
7486				$block.each(function () {
7487					let $this = $(this);
7488					let mediaGap = $this.data('marquee-margin');
7489					let mediaPerPage = $this.data('marquee-count');
7490					let margueeDrag = $this.data('marquee-drag');
7491					let margueePause = $this.data('marquee-pause');
7492					let margueeSpeed = $this.data('marquee-speed');
7493					let margueeReverse = $this.data('marquee-revese');
7494	
7495					let autoScrollSpeed = (margueeReverse === true || margueeReverse === 'true') ? -margueeSpeed : margueeSpeed;
7496		
7497					if ($(this).data('move')) {
7498						var $mediaMove = $(this).data('move');
7499					} else {
7500						var $mediaMove = 1;
7501					}
7502		
7503					if ($this.find('.splide').not('.is-active').length != 0) {
7504		
7505						$this.find('.splide').not('.is-active').each(function () {
7506						
7507							let splide = new Splide($(this)[0], {
7508								type: 'loop',
7509								drag: margueeDrag,
7510								focus: 'center',
7511								arrows: false,
7512								pagination: false,
7513								perMove: $mediaMove,
7514								perPage: checkInitPerPage(),
7515								lazyLoad: 'nearby',
7516								autoScroll: {
7517									speed: autoScrollSpeed,
7518									pauseOnHover: margueePause,
7519									pauseOnFocus: margueePause,
7520								}
7521							});
7522							
7523							splide.mount(window.splide.Extensions);
7524		
7525							sliderBreakPoints();
7526		
7527							document.addEventListener('dataMediaSourceChange', sliderBreakPoints);
7528		
7529							function sliderBreakPoints() {
7530								let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
7531		
7532								switch (dataMediaSource) {
7533									case 'media-xl':
7534										splide.options = {
7535											gap: mediaGap[0],
7536											perPage: mediaPerPage[0],
7537										};
7538										break;
7539									case 'media-lg':
7540										splide.options = {
7541											gap: mediaGap[1],
7542											perPage: mediaPerPage[1],
7543										};
7544										break;
7545									case 'media-md':
7546										splide.options = {
7547											gap: mediaGap[2],
7548											perPage: mediaPerPage[2],
7549										};
7550										break;
7551									case 'media-sm':
7552										splide.options = {
7553											gap: mediaGap[3],
7554											perPage: mediaPerPage[3],
7555										};
7556										break;
7557									case 'media-xs':
7558										splide.options = {
7559											gap: mediaGap[4],
7560											perPage: mediaPerPage[4],
7561										};
7562										break;
7563								}
7564							};
7565		
7566							function checkInitPerPage() {
7567								let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
7568		
7569								switch (dataMediaSource) {
7570									case 'media-xl':
7571										return mediaPerPage[0]
7572										break;
7573									case 'media-lg':
7574										return mediaPerPage[1]
7575										break;
7576									case 'media-md':
7577										return mediaPerPage[2]
7578										break;
7579									case 'media-sm':
7580										return mediaPerPage[3]
7581										break;
7582									case 'media-xs':
7583										return mediaPerPage[4]
7584										break;
7585								};
7586							};
7587						});
7588					}
7589				});
7590			}
7591		
7592		}, 1000);
7593	};
7594	
7595	
7596	lpc_template.queue.wizardStepForm = function ($self) {
7597		
7598	    let $block = $self.find('.wizard-step-init');
7599	
7600	    if ($block.length) {
7601	        $block.each(function () {
7602	            const wrap = this;
7603	            const stepsWrap = wrap.querySelector(".lpc-wizard-step__steps");
7604	            const coverWrap = wrap.querySelector(".lpc-wizard-cover");
7605	            const coverBtn = wrap.querySelector(".lpc-wizard-cover__btn");
7606	
7607	            const steps = wrap.querySelectorAll(".lpc-wizard-step__options");
7608	            const nextBtn = wrap.querySelector(".lpc-wizard-step__next");
7609	            const prevBtn = wrap.querySelector(".lpc-wizard-step__prev");
7610	            const buttonsWrap = wrap.querySelector(".lpc-wizard-step__button");
7611	            const finalForm = wrap.querySelector(".lpc-wizard-step__standalone-form");
7612	            
7613	            const progressBar = wrap.querySelector(".lpc-wizard-progress__bar");
7614	            const progressCounter = wrap.querySelector(".lpc-wizard-progress__counter");
7615	
7616	            let currentStep = 0;
7617	
7618	            finalForm.style.display = "none";
7619	            
7620	            if (s3LP.is_cms) {
7621			        nextBtn.disabled = false;
7622			        nextBtn.classList.remove("disabled");
7623			    } else {
7624			    	nextBtn.disabled = true;
7625	            	nextBtn.classList.add("disabled");
7626			    }
7627	            
7628	            let allowAutoStep = true;
7629	            steps.forEach(step => {
7630	                if (step.querySelectorAll("input[type='checkbox']").length > 0) {
7631	                    allowAutoStep = false;
7632	                }
7633	            });
7634	
7635	            if (stepsWrap && stepsWrap.classList.contains("_hidden_steps_form")) {
7636	                if (coverWrap) coverWrap.style.display = "block";
7637	            }
7638	
7639	            if (coverBtn) {
7640	                coverBtn.addEventListener("click", function () {
7641	                    stepsWrap.style.display = "block";
7642	                    stepsWrap.classList.remove("_hidden_steps_form");
7643	                    if (coverWrap) coverWrap.style.display = "none";
7644	                    updateSteps();
7645	                });
7646	            }
7647	           
7648	            function getCompletedStepsCount() {
7649	                let completed = 0;
7650	            
7651	                steps.forEach(step => {
7652	                    const inputs = step.querySelectorAll("input[type='radio'], input[type='checkbox'], select");
7653	            
7654	                    const isDone = Array.from(inputs).some(el => {
7655	                        if (el.type === "checkbox") return el.checked;
7656	                        if (el.type === "radio") return el.checked;
7657	                        if (el.tagName === "SELECT") return el.value.trim() !== "";
7658	                    });
7659	            
7660	                    if (isDone) completed++;
7661	                });
7662	            
7663	                return completed;
7664	            }
7665	           
7666	            function updateProgress() {
7667	                const completed = getCompletedStepsCount();
7668	                const percent = (completed / steps.length) * 100;
7669	            
7670	                if (progressBar) {
7671	                    progressBar.style.width = percent + "%";
7672	                }
7673	            
7674	                if (progressCounter) {
7675	                    progressCounter.textContent = `${completed} / ${steps.length}`;
7676	                }
7677	            }
7678	           
7679	            function updateSteps() {
7680	                steps.forEach((step, i) => {
7681	                    step.style.display = i === currentStep ? "flex" : "none";
7682	                });
7683	            
7684	                prevBtn.style.display = currentStep === 0 ? "none" : "inline-block";
7685	                nextBtn.textContent = currentStep === steps.length - 1 ? "Завершить" : "Далее";
7686	            
7687	                updateProgress();
7688	                validateStep();
7689	            }
7690	            
7691	            steps.forEach(step => {
7692	                step.addEventListener("change", () => {
7693	                    updateProgress();
7694	                });
7695	            });
7696	            
7697	            function validateStep() {
7698				    const stepEl = steps[currentStep];
7699				    const isMandatory = stepEl.getAttribute("data-mandatory") === "true";
7700				    
7701				    if (!isMandatory) {
7702				        nextBtn.disabled = false;
7703				        nextBtn.classList.remove("disabled");
7704				        return true;
7705				    }
7706				    
7707				    const currentInputs = stepEl.querySelectorAll("input[type='radio'], input[type='checkbox']");
7708				    const hasChecked = Array.from(currentInputs).some(i => i.checked);
7709				
7710				    nextBtn.disabled = !hasChecked;
7711				    nextBtn.classList.toggle("disabled", !hasChecked);
7712				
7713				    return hasChecked;
7714				}
7715	           
7716	            function getCleanLabelText(input) {
7717	                const label = input.closest("label");
7718	                return label ? label.innerText.trim() : input.value.trim();
7719	            }
7720	           
7721	            function collectWizardDataReadable() {
7722	                let result = [];
7723	
7724	                steps.forEach((step, index) => {
7725	                    const checked = step.querySelectorAll("input:checked");
7726	                    const title = step.querySelector(".lpc-wizard-step__title")?.innerText.trim() || `Шаг-${index + 1}`;
7727	
7728	                    let text = checked.length
7729	                        ? Array.from(checked).map(i => getCleanLabelText(i)).join(", ")
7730	                        : "(не выбран)";
7731	
7732	                    result.push(`${title}: ${text}`);
7733	                });
7734	
7735	                return result.join("; ");
7736	            }
7737	            
7738	            function putDataIntoHiddenField(dataStr) {
7739	                const hiddenInput = finalForm.querySelector('input[data-alias="wizard_data"]');
7740	                if (hiddenInput) hiddenInput.value = dataStr;
7741	            }
7742	           
7743	            steps.forEach(step => step.addEventListener("change", validateStep));
7744	            
7745	            if (allowAutoStep) {
7746				    steps.forEach((step, index) => {
7747				        const radios = step.querySelectorAll("input[type='radio']");
7748				
7749				        if (radios.length) {
7750				            radios.forEach(radio => {
7751				                radio.addEventListener("change", () => {
7752				
7753				                    updateProgress();
7754				
7755				                    if (step.classList.contains("_automatic_step") && currentStep === index) {
7756				
7757				                        if (!validateStep()) return;
7758				                        
7759				                        if (currentStep < steps.length - 1) {
7760				                            currentStep++;
7761				                            updateSteps();
7762				                            updateProgress();
7763				                        } else {
7764				                            if (allowAutoStep) {
7765				                                const dataStr = collectWizardDataReadable();
7766				                                putDataIntoHiddenField(dataStr);
7767				
7768				                                finalForm.style.display = "flex";
7769				                                stepsWrap.style.display = "none";
7770				                                buttonsWrap.style.display = "none";
7771				                            }
7772				                        }
7773				                    }
7774				                });
7775				            });
7776				        }
7777				    });
7778				}
7779	
7780	            nextBtn.addEventListener("click", function () {
7781	                if (!validateStep()) return;
7782	
7783	                if (currentStep < steps.length - 1) {
7784	                    currentStep++;
7785	                    updateSteps();
7786	                    updateProgress();
7787	                } else {
7788	                    const dataStr = collectWizardDataReadable();
7789	                    putDataIntoHiddenField(dataStr);
7790	
7791	                    finalForm.style.display = "flex";
7792	                    stepsWrap.style.display = "none";
7793	                    buttonsWrap.style.display = "none";
7794	                }
7795	            });
7796	
7797	            prevBtn.addEventListener("click", function () {
7798	                if (currentStep > 0) {
7799	                    currentStep--;
7800	                    updateSteps();
7801	                    updateProgress();
7802	                }
7803	            });
7804	
7805	            if (!stepsWrap.classList.contains("_hidden_steps_form")) {
7806	                updateSteps();
7807	            }
7808	
7809	        });
7810	    }
7811	};
7812	
7813	
7814	lpc_template.queue.wizardStepFormPopup = function ($self) {
7815
7816	    let $block = $self.find('.popup-wizard-step-init');
7817	
7818	    if (!$block.length) return;
7819	
7820	    $block.each(function () {
7821	
7822	        const wrap = this;
7823	
7824	        const stepsWrap = wrap.querySelector(".lpc-popup-wizard-step__steps");
7825	        const steps = wrap.querySelectorAll(".lpc-popup-wizard-step__options");
7826	
7827	        const nextBtn = wrap.querySelector(".lpc-popup-wizard-step__next");
7828	        const prevBtn = wrap.querySelector(".lpc-popup-wizard-step__prev");
7829	        const buttonsWrap = wrap.querySelector(".lpc-popup-wizard-step__button");
7830	        const finalForm = wrap.querySelector(".lpc-popup-wizard-step__standalone-form");
7831	
7832	        const progressBar = wrap.querySelector(".lpc-popup-wizard-
7832progress__bar");
7833	        const progressCounter = wrap.querySelector(".lpc-popup-wizard-progress__counter");
7834	
7835	        let currentStep = 0;
7836	
7837	        finalForm.style.display = "none";
7838	        nextBtn.disabled = true;
7839	        nextBtn.classList.add("disabled");
7840	
7841	        let allowAutoStep = true;
7842	        steps.forEach(step => {
7843	            if (step.querySelectorAll("input[type='checkbox']").length > 0) {
7844	                allowAutoStep = false;
7845	            }
7846	        });
7847	        
7848	        
7849	        function applyNoImageFormClass() {
7850				const wrapEl = wrap.closest('.lpc-popup-wizard-step__wrap');
7851				const containerEl = wrap.closest('.lpc-popup-wizard-step__container');
7852	
7853				if (wrapEl && wrapEl.classList.contains('_no_image_form') && containerEl) {
7854					containerEl.classList.add('_width_block');
7855				}
7856			}
7857			
7858			function scrollToCurrentStep() {
7859				if (window.innerWidth > 1024) return;
7860
7861				const container = wrap.closest('.lp-popup-inner.js-popup-inner');
7862				const stepEl = steps[currentStep];
7863				const progressBar = wrap.querySelector('.lpc-popup-wizard-progress__bar');
7864				
7865				if (!container || !stepEl || !progressBar) return;
7866				
7867				setTimeout(() => {
7868					const containerRect = container.getBoundingClientRect();
7869					const progressRect = progressBar.getBoundingClientRect();
7870					
7871					const offset = progressRect.top - containerRect.top + container.scrollTop - 20; // отступ 10px
7872			
7873					container.scrollTo({
7874						top: offset,
7875						behavior: 'smooth'
7876					});
7877				}, 50);
7878			}
7879	
7880	        function getCompletedStepsCount() {
7881	            let completed = 0;
7882	
7883	            steps.forEach(step => {
7884	                const inputs = step.querySelectorAll(
7885	                    "input[type='radio'], input[type='checkbox'], select"
7886	                );
7887	
7888	                const isDone = Array.from(inputs).some(el => {
7889	                    if (el.type === "checkbox") return el.checked;
7890	                    if (el.type === "radio") return el.checked;
7891	                    if (el.tagName === "SELECT") return el.value.trim() !== "";
7892	                });
7893	
7894	                if (isDone) completed++;
7895	            });
7896	
7897	            return completed;
7898	        }
7899	
7900	        function updateProgress() {
7901	            const completed = getCompletedStepsCount();
7902	            const percent = (completed / steps.length) * 100;
7903	
7904	            if (progressBar) {
7905	                progressBar.style.width = percent + "%";
7906	            }
7907	
7908	            if (progressCounter) {
7909	                progressCounter.textContent = `${completed} / ${steps.length}`;
7910	            }
7911	        }
7912	
7913	        function validateStep() {
7914	            const stepEl = steps[currentStep];
7915	            const isMandatory = stepEl.getAttribute("data-mandatory") === "true";
7916	
7917	            if (!isMandatory) {
7918	                nextBtn.disabled = false;
7919	                nextBtn.classList.remove("disabled");
7920	                return true;
7921	            }
7922	
7923	            const inputs = stepEl.querySelectorAll(
7924	                "input[type='radio'], input[type='checkbox']"
7925	            );
7926	
7927	            const hasChecked = Array.from(inputs).some(i => i.checked);
7928	
7929	            nextBtn.disabled = !hasChecked;
7930	            nextBtn.classList.toggle("disabled", !hasChecked);
7931	
7932	            return hasChecked;
7933	        }
7934	
7935	        function updateSteps() {
7936	            steps.forEach((step, i) => {
7937	                step.style.display = i === currentStep ? "flex" : "none";
7938	            });
7939	
7940	            prevBtn.style.display = currentStep === 0 ? "none" : "inline-block";
7941	            nextBtn.textContent =
7942	                currentStep === steps.length - 1 ? "Завершить" : "Далее";
7943	
7944	            updateProgress();
7945	            validateStep();
7946	            
7947	            scrollToCurrentStep(); // ДОБАВИТЬ
7948	        }
7949	
7950	        function getCleanLabelText(input) {
7951	            const label = input.closest("label");
7952	            return label ? label.innerText.trim() : input.value.trim();
7953	        }
7954	
7955	        function collectWizardDataReadable() {
7956	            let result = [];
7957	
7958	            steps.forEach((step, index) => {
7959	                const checked = step.querySelectorAll("input:checked");
7960	                const title =
7961	                    step.querySelector(".lpc-popup-wizard-step__options-title")?.innerText.trim() ||
7962	                    `Шаг-${index + 1}`;
7963	
7964	                const text = checked.length
7965	                    ? Array.from(checked)
7966	                        .map(i => getCleanLabelText(i))
7967	                        .join(", ")
7968	                    : "(не выбран)";
7969	
7970	                result.push(`${title}: ${text}`);
7971	            });
7972	
7973	            return result.join("; ");
7974	        }
7975	
7976	        function putDataIntoHiddenField(dataStr) {
7977	            const hiddenInput = finalForm.querySelector(
7978	                'input[data-alias="wizard_data"]'
7979	            );
7980	            if (hiddenInput) hiddenInput.value = dataStr;
7981	        }
7982	
7983	        steps.forEach(step => {
7984	            step.addEventListener("change", () => {
7985	                updateProgress();
7986	                validateStep();
7987	            });
7988	        });
7989	
7990	        if (allowAutoStep) {
7991	            steps.forEach((step, index) => {
7992	                const radios = step.querySelectorAll("input[type='radio']");
7993	
7994	                radios.forEach(radio => {
7995	                    radio.addEventListener("change", () => {
7996	
7997	                        if (!step.classList.contains("_automatic_step")) return;
7998	                        if (currentStep !== index) return;
7999	                        if (!validateStep()) return;
8000	
8001	                        if (currentStep < steps.length - 1) {
8002	                            currentStep++;
8003	                            updateSteps();
8004	                            
8005	                            scrollToCurrentStep(); // ДОБАВИТЬ
8006	                            
8007	                        } else {
8008	                            const dataStr = collectWizardDataReadable();
8009	                            putDataIntoHiddenField(dataStr);
8010	
8011	                            finalForm.style.display = "flex";
8012	                            stepsWrap.style.display = "none";
8013	                            buttonsWrap.style.display = "none";
8014	                            
8015	                            applyNoImageFormClass(); // ДОБАВЛЕНО
8016	                        }
8017	                    });
8018	                });
8019	            });
8020	        }
8021	
8022	        nextBtn.addEventListener("click", () => {
8023	            if (!validateStep()) return;
8024	
8025	            if (currentStep < steps.length - 1) {
8026	                currentStep++;
8027	                updateSteps();
8028	                
8029	                scrollToCurrentStep(); // ДОБАВИТЬ
8030	                
8031	            } else {
8032	                const dataStr = collectWizardDataReadable();
8033	                putDataIntoHiddenField(dataStr);
8034	
8035	                finalForm.style.display = "flex";
8036	                stepsWrap.style.display = "none";
8037	                buttonsWrap.style.display = "none";
8038	                
8039	                applyNoImageFormClass(); // ДОБАВЛЕНО
8040	            }
8041	        });
8042	
8043	        prevBtn.addEventListener("click", () => {
8044	            if (currentStep > 0) {
8045	                currentStep--;
8046	                updateSteps();
8047	            }
8048	        });
8049	
8050	        updateSteps();
8051	
8052	    });
8053	};
8054	
8055	
8056	lpc_template.queue.masonGallery = function ($self) {
8057	    let $block = $self.find('.lpc-masonry-init');
8058	
8059	    if ($block.length) {
8060	        $block.each(function () {
8061	            let $this = $(this);
8062	            let listbox = $this.find(".lpc-image-mason__list");
8063	            let lazyItems = $this.find(".lpc-image-mason__item img[data-src]");
8064	            let windowHeight = $(window).height();
8065	
8066	            function loadVisibleItems() {
8067	                lazyItems.each(function (index, item) {
8068	                    const rect = item.getBoundingClientRect();
8069	
8070	                    if (rect.top < windowHeight) {
8071	                        const img = $(item);
8072	
8073	                        if (!img.hasClass('is-loaded')) {
8074	                            img.on('load', function () {
8075	                                img.closest('.lpc-image-mason__item').addClass('is-show');
8076	                                resizeGridItem(img.closest('.lpc-image-mason__item'));
8077	                            });
8078	
8079	                            img.attr('src', img.data('src'));
8080	                            img.addClass('is-loaded');
8081	                        }
8082	                    }
8083	                });
8084	
8085	                lazyItems = $this.find(".lpc-image-mason__item img[data-src]");
8086	            }
8087	
8088	            function resizeGridItem(item) {
8089	                let grid = $this.find('.lpc-image-mason__list');
8090	                let rowHeight = parseInt(grid.css("grid-auto-rows"));
8091	                let rowGap = parseInt(grid.css("grid-row-gap"));
8092	
8093	                let rowSpan = Math.ceil(
8094	                    (item.find('.lpc-image-mason__image').outerHeight() + rowGap) / (rowHeight + rowGap)
8095	                );
8096	                item.css("grid-row-end", "span " + rowSpan);
8097	
8098	                let image = item.find('.lpc-image-mason__image');
8099	                image.css("height", "100%");
8100	            }
8101	
8102	            $(window).on('scroll', function () {
8103	                loadVisibleItems();
8104	            });
8105	
8106	            loadVisibleItems();
8107	        });
8108	    }
8109	};
8110	
8111	lpc_template.queue.dinamicPadding = function ($self) {
8112	    let $block = $self.find('.lpc-vertical-wrap');
8113	
8114	    if ($block.length) {
8115	        let item = $block.find('.lpc-timeline-vertical__item');
8116	
8117	        function updatePadding() {
8118	            item.each(function() {
8119	                let $this = $(this);
8120	                let numBlock = $this.find('#numBlock');
8121	                let bodyBlock = $this.find('#bodyBlock');
8122	                let stringBlock = $this.find('#stringBlock');
8123
8124					if (stringBlock.length) {
8125						let numBlockHeight = numBlock.outerHeight() / 2 - stringBlock.outerHeight() / 2;
8126		                bodyBlock.css('padding-top', `${numBlockHeight}px`);
8127					}
8128	            });
8129	        }
8130	
8131	        updatePadding();
8132			
8133			if (!s3LP.is_cms) {
8134				let resizeTimeout;
8135
8136				$(window).on('resize', function () {
8137					if (resizeTimeout) {
8138						clearTimeout(resizeTimeout);
8139					}
8140
8141					resizeTimeout = setTimeout(function () {
8142						updatePadding();
8143					}, 50);
8144				});
8145			};
8146	    }
8147	};
8148	
8149	lpc_template.queue.visibleBlock = function ($self) {
8150		var $block = $self.find('.lpc-opacity-block');
8151	
8152		if (!s3LP.is_cms) {
8153			
8154			var $images = $self.find('lpc-promotion-slider__image img, .lpc-form-substrate__background img');
8155		
8156			function removeOpacityClass() {
8157				$block.removeClass('lpc-opacity-block');
8158			}
8159			
8160			var imageCount = $images.length;
8161			
8162			if (imageCount === 0) {
8163				removeOpacityClass();
8164				
8165			} else {
8166				
8167				$images.each(function () {
8168	                if (this.complete) {
8169	                    imageCount--;
8170	                } else {
8171	                    $(this).on('load', function () {
8172	                        imageCount--;
8173	                        
8174	                        if (imageCount === 0) {
8175	                            removeOpacityClass();
8176	                        }
8177	                    });
8178	                }
8179	            });
8180	
8181				if (imageCount === 0) {
8182					removeOpacityClass();
8183				}
8184			}
8185		}
8186	};
8187	
8188	lpc_template.queue.constructorClick = function ($self) {
8189		let $block = $self.find('.lpc-constructor');
8190	
8191		if ($block.length) {
8192			$block.each(function () {
8193				let $this = $(this);
8194				let lpcClick = $this.find(".lpc-active-click");
8195				let item = $this.find(".lpc-constructor-click");
8196	
8197				if (s3LP.is_cms) {
8198					lpcClick.on('click', function () {
8199						item.toggleClass('lpc-image-show');
8200					});
8201				}
8202			});
8203		}
8204	};
8205	
8206	lpc_template.queue.tabsConditions = function ($self) {
8207		let $block = $self.find('.conditions-tabs-init');
8208	
8209		if (!$block.length) return;
8210	
8211		$block.each(function () {
8212			let $this = $(this);
8213	
8214			let $buttons = $this.find('._tabs-button');
8215			let $items = $this.find('._tabs-item');
8216			let $lpButton = $this.find('.lp-button');
8217			let $head = $this.find('.lpc-conditions__head');
8218	
8219			let isGroup = $head.hasClass('_group_active');
8220	
8221			if ($head.hasClass('_type-group')) {
8222				$head.css('border-radius', $lpButton.css('border-radius'));
8223			}
8224	
8225			if (!isGroup) {
8226				$buttons.on('click', function () {
8227					let $button = $(this);
8228					let index = $button.data('index');
8229	
8230					$buttons.removeClass('active');
8231					$button.addClass('active');
8232	
8233					$items.each(function () {
8234						let $item = $(this);
8235						$item.toggleClass('active', $item.data('index') == index);
8236					});
8237				});
8238	
8239				return;
8240			}
8241	
8242			function syncButtonTypes() {
8243				$buttons
8244					.removeClass('lpc-button--type-1 lpc-button--type-2')
8245					.addClass('lpc-button--type-2');
8246	
8247				$buttons.filter('.active')
8248					.removeClass('lpc-button--type-2')
8249					.addClass('lpc-button--type-1');
8250			}
8251	
8252			$buttons.on('click', function () {
8253				let $button = $(this);
8254				let index = $button.data('index');
8255	
8256				let isActive = $button.hasClass('active');
8257	
8258				if (isActive) {
8259					$button.removeClass('active');
8260				} else {
8261					$buttons.removeClass('active');
8262					$button.addClass('active');
8263				}
8264	
8265				$items.each(function () {
8266					let $item = $(this);
8267					$item.toggleClass('active', $item.data('index') == index && !isActive);
8268				});
8269	
8270				syncButtonTypes();
8271			});
8272			
8273			syncButtonTypes();
8274		});
8275	};
8276	
8277	lpc_template.queue.tabsInit = function ($self) {
8278        let $block = $self.find('.lpc-tabs-init');
8279    
8280        if ($block.length) {
8281            $block.each(function () {
8282                let $this = $(this);
8283                let $tab = $this.find('.lpc-tabs-title');
8284                let $acc = $this.find('.lpc-accord-title');
8285                let $body = $this.find('.lpc-tabs-body');
8286                let blockId = $this.data('blockId');
8287                let isVertical = $this.hasClass('lpc-tabs-vertical');
8288                let hasTabManager = $this.hasClass('lpc-tab-manager');
8289    
8290                function accord() {
8291                    $tab.off('click.tabs');
8292                    $acc.off('click.accorDeon').on('click.accorDeon', function () {
8293                        let $currentAcc = $(this);
8294                        let $currentBody = $currentAcc.next('.lpc-tabs-body');
8295                        let isActive = $currentAcc.hasClass('active');
8296    
8297                        $acc.removeClass('active');
8298                        $body.slideUp(200).removeClass('active');
8299    
8300                        if (!isActive) {
8301                            $currentAcc.addClass('active');
8302                            $currentBody.slideDown(200).addClass('active');
8303                            
8304                            if (hasTabManager) {
8305	                            let index = $currentAcc.data('index');
8306	                            localStorage.setItem('activeTab_' + blockId, index);
8307                            }
8308                        }
8309    
8310                        if ($currentAcc.hasClass('active')) {
8311                            setTimeout(function(){
8312                                $('html, body').stop().animate({
8313                                    scrollTop: $currentAcc.offset().top - 50
8314                                }, 500);
8315                            }, 301);
8316                        }
8317                    });
8318                }
8319    
8320                function tabs() {
8321                    $acc.off('click.accorDeon');
8322                    $tab.off('click.tabs').on('click.tabs', function () {
8323                        let $currentTab = $(this);
8324                        let index = $currentTab.data('index');
8325                        let $currentBody = $this.find('.lpc-tabs-body[data-index="' + index + '"]');
8326    
8327                        if (!$currentTab.hasClass('active')) {
8328                            $tab.removeClass('active');
8329                            $body.removeClass('active');
8330                            $currentTab.addClass('active');
8331                            $currentBody.addClass('active');
8332    						
8333    						if (hasTabManager) {
8334                            	localStorage.setItem('activeTab_' + blockId, index);
8335    						}
8336                        }
8337                    });
8338                }
8339    
8340                function updateActiveTab() {
8341                    let dataMedia = document.querySelector('.decor-wrap').dataset.mediaSource;
8342    
8343                    if ((isVertical && (dataMedia === 'media-md' || dataMedia === 'media-sm' || dataMedia === 'media-xs')) || (!isVertical && dataMedia === 'media-xs')) {
8344                        accord();
8345                    } else {
8346                        tabs();
8347                    }                   
8348    
8349    				if (hasTabManager) {
8350	                    let activeBlockId = localStorage.getItem('activeTab_' + blockId);
8351	                    let index = parseInt(activeBlockId, 10) || 0;
8352	    
8353	                    if ((isVertical && (dataMedia === 'media-md' || dataMedia === 'media-sm' || dataMedia === 'media-xs')) || (!isVertical && dataMedia === 'media-xs')) {
8354	                        $acc.removeClass('active');
8355	                        $body.hide().removeClass('active');
8356	    
8357	                        $acc.eq(index).addClass('active');
8358	                        $body.eq(index).toggle().addClass('active');
8359	    
8360	                    } else {
8361	                        $tab.removeClass('active').removeAttr('style');
8362	                        $body.removeClass('active').removeAttr('style');
8363	    
8364	                        $tab.eq(index).addClass('active').removeAttr('style');
8365	                        $body.eq(index).addClass('active').removeAttr('style');
8366	                    }
8367    				}
8368                }
8369    
8370                updateActiveTab();
8371 
8372                window.addEventListener('orientationchange', function () {
8373                    setTimeout(function () {
8374                        updateActiveTab();
8375                    }, 300); 
8376                });
8377            });
8378        }
8379    };
8380    
8381    lpc_template.queue.sliderBlockTabs = function ($self) {
8382	    let $block = $self.attr('data-slider-tabs-init') ? $self : $self.find('[data-slider-tabs-init]');
8383	    
8384	    if ($block.length) {
8385	        if ($block.data('data-slider-tabs-init') != true) {
8386	
8387	            $block.each(function () {
8388	                let $this = $(this);
8389	                let $alignItem = $this.find($this.data('align-item'));
8390	
8391	                let $splideEl = $this.find('.splide:not(.is-active)').first();
8392	                if (!$splideEl.length) return;
8393	                
8394	                let splide = new Splide($splideEl[0], {
8395	                    autoplay: $this.data('autoplay'),
8396	                    speed: $this.data('speed'),
8397	                    interval: $this.data('pause'),
8398	                    rewind: true,
8399	                    lazyLoad: $this.data('lazy-load'),
8400	                    perPage: 1,
8401	                    perMove: 1,
8402	                    gap: 20,
8403	                    pagination: false
8404	                });
8405	               
8406	                let $customPagination = $this.find('.splide__custom__pagination');
8407	                let $customButtons = $customPagination.find('.splide__pagination__page');
8408	
8409	                $customButtons.each(function (index) {
8410	                    $(this).on('click', function () {
8411	                        splide.go(index);
8412	                    });
8413	                });
8414	
8415	                splide.on('move mounted', function () {
8416	                    let active = splide.index;
8417	                    $customButtons.removeClass('is-active');
8418	                    $customButtons.eq(active).addClass('is-active');
8419	                });
8420	
8421	                splide.mount();
8422	
8423	                sliderBreakPoints();
8424	                
8425	                document.addEventListener('lpcPopupOpened', function () {
8426	                    splide.refresh();
8427	                });
8428	
8429	                document.addEventListener('dataMediaSourceChange', sliderBreakPoints);
8430	
8431	                function sliderBreakPoints() {
8432	                    let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
8433	
8434	                    setTimeout(function () {
8435	                        if ($alignItem.length) {
8436	                            let itemHeight = $alignItem.outerHeight() / 2;
8437	                            let arrowsPosition = itemHeight + $alignItem.position().top;
8438	                            $this.find('.splide__arrow').css('top', arrowsPosition);
8439	                        }
8440	                    }, 100);
8441	                    
8442	                    switch (dataMediaSource) {
8443	                        case 'media-xl':
8444	                        case 'media-lg':
8445	                            splide.options = {
8446	                                arrows: true,
8447	                                perPage: 1,
8448	                                gap: 20,
8449	                            };
8450	                        break;
8451	
8452	                        case 'media-md':
8453	                            splide.options = {
8454	                                arrows: false,
8455	                                perPage: 1,
8456	                                gap: 20,
8457	                            };
8458	                        break;
8459	
8460	                        case 'media-sm':
8461	                        case 'media-xs':
8462	                            splide.options = {
8463	                                arrows: false,
8464	                                rewindByDrag: true,
8465	                                perPage: 1,
8466	                                gap: 16,
8467	                            };
8468	                        break;
8469	                    }
8470	                }
8471	            });
8472	        }
8473	    }
8474	};
8475	
8476	lpc_template.queue.initVideoBlocks = function () {
8477		/*const blocks = document.querySelectorAll(".lpc-block");
8478	
8479		blocks.forEach((block) => {
8480			const videoPosters = block.querySelectorAll(".lpc-video-poster");
8481			const videoContainers = block.querySelectorAll(".lpc-video-container");
8482	
8483			videoPosters.forEach((videoPoster, index) => {
8484				const iframe = videoContainers[index].querySelector("iframe");
8485	
8486				videoPoster.addEventListener("click", function () {
8487					const dataSrc = videoPoster.getAttribute("data-youtube-id");
8488	
8489					if (dataSrc) {
8490						iframe.setAttribute("src", "https://www.youtube.com/embed/" + dataSrc + "?autoplay=1&mute=0");
8491						videoPoster.removeAttribute("data-youtube-id");
8492						videoPoster.style.display = "none";
8493						videoContainers[index].style.display = "block";
8494					}
8495				});
8496			});
8497		});*/
8498		const blocks = document.querySelectorAll(".lpc-block");
8499		
8500	    blocks.forEach((block) => {
8501	        const videoPosters = block.querySelectorAll(".lpc-video-poster");
8502	        const videoContainers = block.querySelectorAll(".lpc-video-container");
8503	
8504	        videoPosters.forEach((videoPoster, index) => {
8505	            
8506	            videoPoster.addEventListener("click", function () {
8507	                let _this = this;
8508	                let parent = _this.closest('.lp-video-block-wrappper');
8509	                let container = parent.querySelector(".lpc-video-container");
8510	                let iframe = container.querySelector("iframe");
8511	                let src = iframe.getAttribute("data-src").replace('autoplay=0','autoplay=1');
8512	                
8513	                iframe.setAttribute("src", src);
8514	                videoPoster.style.display = "none";
8515	                container.style.display = "block";
8516	            });
8517	        });
8518	    });
8519	};
8520	
8521	document.addEventListener("lpc_init_after", function () { // вместо  DOMContentLoaded используем lpc_init_after чтобы работало в новом конструкторе, так как там нет события DOMContentLoaded
8522		lpc_template.queue.initVideoBlocks();
8523	});
8524
8525	document.addEventListener("lpc_init_after", function () {
8526		// Функция для обновления window.s3LP за пределами айфрейма 
8527		// https://staff.megagroup.ru/staff/sites/?site_id=8861349 используется в файле /g/s3/lp/lpc_tpl/js/lpc_tpl_main.js
8528		// для того чтобы проверять из внешнего файла находимся мы в конструкторе или нет и что-то делать
8529		function syncS3LPToTop() {
8530		    try {
8531		        if (window.top && window.top !== window && window.s3LP) {
8532		            window.top.s3LP = window.s3LP;
8533		        }
8534		    } catch (e) {
8535		        console.warn('Нет доступа к window.top', e);
8536		    }
8537		}
8538
8539		// использование
8540		syncS3LPToTop(); 
8541	});
8542	
8543	lpc_template.queue.sliderReviews = function ($self) {
8544		let $block = $self.attr('data-slider-reviews-init') ? $self : $self.find('[data-slider-reviews-init]');
8545	
8546		if ($block.length) {
8547			$block.each(function () {
8548				let $this = $(this);
8549				let $alignItem = $this.find($this.data('align-item'));
8550	
8551				if ($this.find('.splide').not('.is-active').length != 0) {
8552					$this.find('.splide').not('.is-active').each(function () {
8553						
8554						let splide = new Splide($(this)[0], {
8555							autoplay: $this.data('autoplay'),
8556							speed: $this.data('speed'),
8557							interval: $this.data('pause'),
8558							lazyLoad: $this.data('lazy-load'),
8559							rewind: true,
8560							arrows: true,
8561							pagination: true,
8562							gap: 0,
8563							perPage: 1
8564						});
8565						
8566						splide.mount();
8567						
8568						if ($(this).find('.lpc-reviews-4__item').length <= 1) {
8569							$(this).addClass('splide--pointer-events');
8570						}
8571					});
8572				}
8573			});
8574		}
8575	};
8576	
8577	lpc_template.queue.sliderBlockBanner = function ($self) {
8578	    let $block = $self.attr('data-slider-banner-init') ? $self : $self.find('[data-slider-banner-init]');
8579	    if ($block.length) {
8580		if ($block.data('slider-thumb-init') != true) {
8581	        $block.each(function(){
8582	            let $this = $(this);
8583				let $alignItem = $this.find($this.data('align-item'));
8584				let mediaGap = $this.data('margin');
8585				let mediaPerPage = $(this).data('count');
8586				if ($(this).data('move')) {
8587					var $mediaMove = $(this).data('move');
8588					
8589				} else {
8590					var $mediaMove = 1;
8591				}
8592
8593	            if($this.find('.splide').not('.is-active').length != 0) {
8594	                let splide = new Splide( $this.find('.splide').not('.is-active')[0], {
8595						autoplay: $this.data('autoplay'),
8596						speed: $this.data('speed'),
8597						interval: $this.data('pause'),
8598	                    lazyLoad: $this.data('lazy-load'),
8599	                    rewind: true,
8600	                    perMove: $mediaMove,
8601						perPage: checkInitPerPage()
8602	                });
8603	                splide.mount();
8604	                
8605					sliderBreakPoints();
8606					
8607					document.addEventListener('lpcPopupOpened', function(){
8608						splide.refresh();
8609					});
8610					
8611					document.addEventListener('dataMediaSourceChange', sliderBreakPoints);
8612					
8613					function sliderBreakPoints() {
8614		                let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
8615		
8616						setTimeout(function(){
8617							if ($alignItem.length) {
8618								let itemHeight = $alignItem.outerHeight() / 2;
8619								let arrowsPosition = itemHeight + $alignItem.position().top;
8620	
8621								$this.find('.splide__arrow').css('top', arrowsPosition);
8622							}
8623						}, 100);
8624						
8625		                switch (dataMediaSource) {
8626		                    case 'media-xl':
8627		                        splide.options = {
8628									arrows: true,
8629									pagination: true,
8630		                            gap: mediaGap[0],
8631		                            perPage: mediaPerPage[0],
8632		                        };
8633		
8634		                        break;
8635		                    case 'media-lg':
8636		                        splide.options = {
8637									arrows: true,
8638									pagination: true,
8639		                            gap: mediaGap[1],
8640		                            perPage: mediaPerPage[1],
8641		                        };
8642		
8643		                        break;
8644		                    case 'media-md':
8645		                        splide.options = {
8646									arrows: true,
8647									pagination: true,
8648		                            gap: mediaGap[2],
8649		                            perPage: mediaPerPage[2],
8650		                        };
8651		
8652		                        break;
8653		                    case 'media-sm':
8654		                        splide.options = {
8655									arrows: true,
8656									pagination: true,
8657		                            gap: mediaGap[3],
8658		                            perPage: mediaPerPage[3],
8659		                        };
8660		
8661		                        break;
8662		                    case 'media-xs':
8663		                        splide.options = {
8664									arrows: true,
8665									pagination: true,
8666		                            gap: mediaGap[4],
8667		                            perPage: mediaPerPage[4],
8668		                        };
8669		                        
8670		                        break;
8671		                }
8672					};
8673					
8674					function checkInitPerPage() {
8675						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
8676					
8677						switch (dataMediaSource) {
8678							case 'media-xl':
8679								return mediaPerPage[0]
8680								break;
8681							case 'media-lg':
8682								return mediaPerPage[1]
8683								break;
8684							case 'media-md':
8685								return mediaPerPage[2]
8686								break;
8687							case 'media-sm':
8688								return mediaPerPage[3]
8689								break;
8690							case 'media-xs':
8691								return mediaPerPage[4]
8692								break;
8693						};
8694					};
8695	            }
8696	        });
8697	    }
8698	    }
8699	};
8700	 	
8701	lpc_template.queue.sliderBlock = function ($self) {
8702		
8703	    let $block = $self.attr('data-slider-init') ? $self : $self.find('[data-slider-init]');
8704	    
8705	    if ($block.length) {
8706		if ($block.data('slider-thumb-init') != true) {
8707	        $block.each(function(){
8708	            let $this = $(this);
8709				let $alignItem = $this.find($this.data('align-item'));
8710				let mediaGap = $this.data('margin');
8711				let mediaPerPage = $(this).data('count');
8712				
8713				if ($(this).data('move')) {
8714					var $mediaMove = $(this).data('move');
8715					
8716				} else {
8717					var $mediaMove = 1;
8718				}
8719
8720	            if($this.find('.splide').not('.is-active').length != 0) {
8721	            	let $splideElem = $this.find('.splide').not('.is-active');
8722					let slidesCount = $splideElem.find('.splide__slide').length;
8723					
8724					function getSliderBehaviorConfig() {
8725						let currentPerPage = checkInitPerPage();
8726						let isDragAvailable = slidesCount > currentPerPage;
8727					
8728						return {
8729							perPage: currentPerPage,
8730							drag: isDragAvailable && !$this.data('drag'),
8731							clones: isDragAvailable ? undefined : 0,
8732							pagination: isDragAvailable
8733						};
8734					}
8735					
8736	                let splide = new Splide($splideElem[0], $.extend({
8737						autoplay: $this.data('autoplay'),
8738						speed: $this.data('speed'),
8739						interval: $this.data('pause'),
8740	                    rewind: $this.data('infinite'),
8741	                    lazyLoad: $this.data('lazy-load'),
8742	                    rewind: true,
8743	                    /*rewindByDrag: true,*/
8744	                    perMove: $mediaMove,
8745	                    drag: !$this.data('drag'),
8746						noDrag: '.no-drag',	
8747						perPage: checkInitPerPage()
8748	                }, getSliderBehaviorConfig()));
8749					
8750	                splide.mount();
8751					sliderBreakPoints();
8752					
8753					function SafeGliderUpdate() {
8754						splide.options = getSliderBehaviorConfig();
8755						splide.refresh();
8756					}
8757					
8758					document.addEventListener('lpcPopupOpened',  SafeGliderUpdate);
8759					document.addEventListener('dataMediaSourceChange', function() {
8760						sliderBreakPoints();
8761						SafeGliderUpdate();
8762					});
8763					
8764					function sliderBreakPoints() {
8765		                let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
8766		
8767						setTimeout(function(){
8768							if ($alignItem.length) {
8769								let itemHeight = $alignItem.outerHeight() / 2;
8770								let arrowsPosition = itemHeight + $alignItem.position().top;
8771	
8772								$this.find('.splide__arrow').css('top', arrowsPosition);
8773							}
8774						}, 100);
8775						
8776		                switch (dataMediaSource) {
8777		                    case 'media-xl':
8778		                        splide.options = {
8779									arrows: true,
8780									pagination: true,
8781		                            gap: mediaGap[0],
8782		                            perPage: mediaPerPage[0],
8783		                        };
8784		
8785		                        break;
8786		                    case 'media-lg':
8787		                        splide.options = {
8788									arrows: true,
8789									pagination: true,
8790		                            gap: mediaGap[1],
8791		                            perPage: mediaPerPage[1],
8792		                        };
8793		
8794		                        break;
8795		                    case 'media-md':
8796		                        splide.options = {
8797									arrows: false,
8798									pagination: true,
8799		                            gap: mediaGap[2],
8800		                            perPage: mediaPerPage[2],
8801		                        };
8802		
8803		                        break;
8804		                    case 'media-sm':
8805		                        splide.options = {
8806									arrows: false,
8807									pagination: true,
8808									/*rewindByDrag: true,*/
8809		                            gap: mediaGap[3],
8810		                            perPage: mediaPerPage[3],
8811		                        };
8812		
8813		                        break;
8814		                    case 'media-xs':
8815		                        splide.options = {
8816									arrows: false,
8817									pagination: true,
8818									/*rewindByDrag: true,*/
8819		                            gap: mediaGap[4],
8820		                            perPage: mediaPerPage[4],
8821		                        };
8822		                        
8823		                        break;
8824		                }
8825					};
8826					
8827					function checkInitPerPage() {
8828						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
8829					
8830						switch (dataMediaSource) {
8831							case 'media-xl':
8832								return mediaPerPage[0]
8833								break;
8834							case 'media-lg':
8835								return mediaPerPage[1]
8836								break;
8837							case 'media-md':
8838								return mediaPerPage[2]
8839								break;
8840							case 'media-sm':
8841								return mediaPerPage[3]
8842								break;
8843							case 'media-xs':
8844								return mediaPerPage[4]
8845								break;
8846						};
8847					};
8848	            }
8849	        });
8850	    }
8851	    }
8852	};
8853	
8854	lpc_template.queue.variableSlider = function ($self) {
8855
8856		let $block = $self.attr('data-variable-slider-init') ? $self : $self.find('[data-variable-slider-init]');
8857	
8858		if ($block.length) {
8859			if ($block.data('data-variable-slider-init') != true) {
8860	
8861				$block.each(function () {
8862					let $this = $(this);
8863					let $alignItem = $this.find($this.data('align-item'));
8864					let focus = $this.data('focus');
8865					let mediaGap = $this.data('margin');
8866					
8867					if ($(this).data('move')) {
8868						var $mediaMove = $(this).data('move');
8869						
8870					} else {
8871						var $mediaMove = 1;
8872					}
8873	
8874					if ($this.find('.splide').not('.is-active').length != 0) {
8875						let splide = new Splide($this.find('.splide').not('.is-active')[0], {
8876							autoplay: $this.data('autoplay'),
8877							speed: $this.data('speed'),
8878							interval: $this.data('pause'),
8879		                    rewind: $this.data('infinite'),
8880		                    lazyLoad: $this.data('lazy-load'),
8881		                    rewind: true,
8882							focus: $this.data('focus'),
8883	  						autoWidth: true,
8884	  						perMove: $mediaMove,
8885						});
8886	
8887						splide.mount();
8888		                
8889						sliderBreakPoints();
8890						
8891						document.addEventListener('lpcPopupOpened', function(){
8892							splide.refresh();
8893						});
8894						
8895						document.addEventListener('dataMediaSourceChange', sliderBreakPoints);
8896						
8897						function sliderBreakPoints() {
8898							
8899			                let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
8900			
8901							setTimeout(function(){
8902								if ($alignItem.length) {
8903									let itemHeight = $alignItem.outerHeight() / 2;
8904									let arrowsPosition = itemHeight + $alignItem.position().top;
8905		
8906									$this.find('.splide__arrow').css('top', arrowsPosition);
8907								}
8908							}, 100);
8909							
8910			                switch (dataMediaSource) {
8911			                    case 'media-xl':
8912			                        splide.options = {
8913										arrows: true,
8914										pagination: true,
8915			                            gap: mediaGap[0],
8916			                        };
8917			
8918			                        break;
8919			                    case 'media-lg':
8920			                        splide.options = {
8921										arrows: true,
8922										pagination: true,
8923			                            gap: mediaGap[1],
8924			                        };
8925			
8926			                        break;
8927			                    case 'media-md':
8928			                        splide.options = {
8929										arrows: false,
8930										pagination: true,
8931			                            gap: mediaGap[2],
8932			                        };
8933			
8934			                        break;
8935			                    case 'media-sm':
8936			                        splide.options = {
8937										arrows: false,
8938										pagination: true,
8939			                            gap: mediaGap[3],
8940			                        };
8941			
8942			                        break;
8943			                    case 'media-xs':
8944			                        splide.options = {
8945										arrows: false,
8946										pagination: true,
8947			                            gap: mediaGap[4],
8948			                        };
8949			                        
8950			                        break;
8951			                }
8952						};
8953					}
8954				});
8955			}
8956		}
8957	};
8958	
8959	lpc_template.queue.sliderTabBlock = function ($self) {
8960		
8961	    let $block = $self.attr('data-slider-tab-init') ? $self : $self.find('[data-slider-tab-init]');
8962	    
8963	    if ($block.length) {
8964		if ($block.data('slider-thumb-init') != true) {
8965	        $block.each(function(){
8966	            let $this = $(this);
8967				let $alignItem = $this.find($this.data('align-item'));
8968				let mediaGap = $this.data('margin');
8969				let mediaPerPage = $(this).data('count');
8970				if ($(this).data('move')) {
8971					var $mediaMove = $(this).data('move');
8972					
8973				} else {
8974					var $mediaMove = 1;
8975				}
8976
8977	            if($this.find('.splide').not('.is-active').length != 0) {
8978	                let splide = new Splide( $this.find('.splide').not('.is-active')[0], {
8979						autoplay: $this.data('autoplay'),
8980						speed: $this.data('speed'),
8981						interval: $this.data('pause'),
8982	                    rewind: $this.data('infinite'),
8983	                    lazyLoad: $this.data('lazy-load'),
8984	                    rewind: true,
8985	                    rewindByDrag: true,
8986						autoWidth: true,
8987	                    perMove: $mediaMove,
8988						perPage: checkInitPerPage()
8989	                });
8990	                splide.mount();
8991	                
8992					sliderBreakPoints();
8993					
8994					document.addEventListener('lpcPopupOpened', function(){
8995						splide.refresh();
8996					});
8997					
8998					document.addEventListener('dataMediaSourceChange', sliderBreakPoints);
8999					
9000					function sliderBreakPoints() {
9001		                let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9002		
9003						setTimeout(function(){
9004							if ($alignItem.length) {
9005								let itemHeight = $alignItem.outerHeight() / 2;
9006								let arrowsPosition = itemHeight + $alignItem.position().top;
9007	
9008								$this.find('.splide__arrow').css('top', arrowsPosition);
9009							}
9010						}, 100);
9011						
9012		                switch (dataMediaSource) {
9013		                    case 'media-xl':
9014		                        splide.options = {
9015									arrows: true,
9016									pagination: false,
9017		                            gap: mediaGap[0],
9018		                            perPage: mediaPerPage[0],
9019		                        };
9020		
9021		                        break;
9022		                    case 'media-lg':
9023		                        splide.options = {
9024									arrows: true,
9025									pagination: false,
9026		                            gap: mediaGap[1],
9027		                            perPage: mediaPerPage[1],
9028		                        };
9029		
9030		                        break;
9031		                    case 'media-md':
9032		                        splide.options = {
9033									arrows: true,
9034									pagination: false,
9035		                            gap: mediaGap[2],
9036		                            perPage: mediaPerPage[2],
9037		                        };
9038		
9039		                        break;
9040		                    case 'media-sm':
9041		                        splide.options = {
9042									arrows: false,
9043									pagination: false,
9044									rewindByDrag: true,
9045		                            gap: mediaGap[3],
9046		                            perPage: mediaPerPage[3],
9047		                        };
9048		
9049		                        break;
9050		                    case 'media-xs':
9051		                        splide.options = {
9052									arrows: false,
9053									pagination: false,
9054									rewindByDrag: true,
9055		                            gap: mediaGap[4],
9056		                            perPage: mediaPerPage[4],
9057		                        };
9058		                        
9059		                        break;
9060		                }
9061					};
9062					
9063					function checkInitPerPage() {
9064						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9065					
9066						switch (dataMediaSource) {
9067							case 'media-xl':
9068								return mediaPerPage[0]
9069								break;
9070							case 'media-lg':
9071								return mediaPerPage[1]
9072								break;
9073							case 'media-md':
9074								return mediaPerPage[2]
9075								break;
9076							case 'media-sm':
9077								return mediaPerPage[3]
9078								break;
9079							case 'media-xs':
9080								return mediaPerPage[4]
9081								break;
9082						};
9083					};
9084	            }
9085	        });
9086	    }
9087	    }
9088	};
9089	
9090	lpc_template.queue.sliderBlockThumb = function ($self) {
9091	    var $block = $self.attr('data-slider-thumb-init') ? $self : $self.find('[data-slider-thumb-init]');
9092	    if ($block.length) {
9093	        $block.each(function(){
9094	            let $this = $(this);
9095				let $alignItem = $this.find($this.data('align-item'));
9096				let mediaGap = $this.data('margin');
9097				let mediaPerPage = $(this).data('count');
9098				let mediaThumbGap = $this.data('thumb-margin');
9099				let mediaThumbFixedWidth = $this.data('thumb-width');
9100				let mediaThumbFixedHeight = $this.data('thumb-height');
9101	                
9102	            if($this.find('#main-slider').not('.is-active').length != 0 ) {
9103	                let splideThumb = new Splide( $this.find('.splide').not('.is-active')[0], {
9104						autoplay: $this.data('autoplay'),
9105						speed: $this.data('speed'),
9106						interval: $this.data('pause'),
9107	                    rewind: $this.data('infinite'),
9108	                    lazyLoad: $this.data('lazy-load'),
9109	                    rewind: true,
9110	                    perMove: 1,
9111						perPage: checkInitPerPage(),
9112						dragMinThreshold: {
9113						    mouse: 5,
9114						    touch: 10,
9115						}	
9116	                });
9117	                
9118	                let thumbnails = new Splide($this.find('.thumbnail-slider').not('.is-active')[0], {
9119					  rewind          : $this.data('rewind'),
9120					  fixedWidth      : checkInitThumbWidth(),
9121					  fixedHeight     : checkInitThumbHeight(),
9122					  isNavigation    : true,
9123					  focus           : $this.data('thumb-focus'),
9124					  pagination      : false,
9125					  cover           : false,
9126					  arrows     	  : $this.data('thumb-arrow'),
9127                	  drag            : false,
9128                	  padding         : 4,
9129					  gap             : checkInitThumbGap(),
9130					  dragMinThreshold: {
9131					    mouse: 5,
9132					    touch: 10,
9133					  }	,
9134					  classes 		  : {
9135					  	arrows: "splide__arrows splide__custom__arrows"
9136					  }
9137					});
9138
9139	                splideThumb.sync( thumbnails );
9140	                
9141	                splideThumb.mount();
9142	                
9143            		thumbnails.mount();
9144                	
9145					sliderBreakPoints();
9146					
9147					sliderPaginationChecking();
9148					
9149					document.addEventListener('dataMediaSourceChange', sliderBreakPoints);
9150					
9151					
9152					
9153					function sliderBreakPoints() {
9154		                let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9155		
9156						setTimeout(function(){
9157							if ($alignItem.length) {
9158								let itemHeight = $alignItem.outerHeight() / 2;
9159								let arrowsPosition = itemHeight + $alignItem.position().top;
9160	
9161								$this.find('.splide__arrow').css('top', arrowsPosition);
9162							}
9163						}, 100);
9164						
9165		                switch (dataMediaSource) {
9166		                    case 'media-xl':
9167		                        splideThumb.options = {
9168									arrows: true,
9169									pagination: true,
9170		                            gap: mediaGap[0],
9171		                            perPage: mediaPerPage[0],
9172		                        };
9173
9174		                        break;
9175		                    case 'media-lg':
9176		                        splideThumb.options = {
9177									arrows: true,
9178									pagination: true,
9179		                            gap: mediaGap[1],
9180		                            perPage: mediaPerPage[1],
9181		                        };
9182		
9183		                        break;
9184		                    case 'media-md':
9185		                        splideThumb.options = {
9186									arrows: true,
9187									pagination: true,
9188		                            gap: mediaGap[2],
9189		                            perPage: mediaPerPage[2],
9190		                        };
9191		                        break;
9192		                    case 'media-sm':
9193		                        splideThumb.options = {
9194									arrows: false,
9195									pagination: true,
9196		                            gap: mediaGap[3],
9197		                            perPage: mediaPerPage[3],
9198		                        };
9199		
9200		                        break;
9201		                    case 'media-xs':
9202		                        splideThumb.options = {
9203									arrows: false,
9204									pagination: true,
9205		                            gap: mediaGap[4],
9206		                            perPage: mediaPerPage[4],
9207		                        };
9208
9209		                        break;
9210		                }
9211		                if($block.data('slider-thumb-init') == true) {
9212							switch (dataMediaSource) {
9213			                    case 'media-xl':
9214			                        thumbnails.options = {
9215			                            gap: mediaThumbGap[0],
9216			                            fixedWidth: mediaThumbFixedWidth[0],
9217			                            fixedHeight: mediaThumbFixedHeight[0],
9218			                        };
9219			
9220			                        break;
9221			                    case 'media-lg':
9222			                        thumbnails.options = {
9223			                            gap: mediaThumbGap[1],
9224			                            fixedWidth: mediaThumbFixedWidth[1],
9225			                            fixedHeight: mediaThumbFixedHeight[1],
9226			                        };
9227			
9228			                        break;
9229			                    case 'media-md':
9230			                        thumbnails.options = {
9231			                            gap: mediaThumbGap[2],
9232			                            fixedWidth: mediaThumbFixedWidth[2],
9233			                            fixedHeight: mediaThumbFixedHeight[2],
9234			                        };
9235			
9236			                        break;
9237			                    case 'media-sm':
9238			                        thumbnails.options = {
9239			                            gap: mediaThumbGap[3],
9240			                            fixedWidth: mediaThumbFixedWidth[3],
9241			                            fixedHeight: mediaThumbFixedHeight[3],
9242			                        };
9243			
9244			                        break;
9245			                    case 'media-xs':
9246			                        thumbnails.options = {
9247			                            gap: mediaThumbGap[4],
9248			                            fixedWidth: mediaThumbFixedWidth[4],
9249			                            fixedHeight: mediaThumbFixedHeight[4],
9250			                        };
9251			                        
9252			                        break;
9253			                }
9254						}
9255					};
9256					
9257					function checkInitPerPage() {
9258						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9259					
9260						switch (dataMediaSource) {
9261							case 'media-xl':
9262								return mediaPerPage[0]
9263								break;
9264							case 'media-lg':
9265								return mediaPerPage[1]
9266								break;
9267							case 'media-md':
9268								return mediaPerPage[2]
9269								break;
9270							case 'media-sm':
9271								return mediaPerPage[3]
9272								break;
9273							case 'media-xs':
9274								return mediaPerPage[4]
9275								break;
9276						};
9277					};
9278					
9279					function checkInitThumbWidth() {
9280						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9281					
9282						switch (dataMediaSource) {
9283							case 'media-xl':
9284								return mediaThumbFixedWidth[0]
9285								break;
9286							case 'media-lg':
9287								return mediaThumbFixedWidth[1]
9288								break;
9289							case 'media-md':
9290								return mediaThumbFixedWidth[2]
9291								break;
9292							case 'media-sm':
9293								return mediaThumbFixedWidth[3]
9294								break;
9295							case 'media-xs':
9296								return mediaThumbFixedWidth[4]
9297								break;
9298						};
9299					};
9300					
9301					function checkInitThumbHeight() {
9302						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9303					
9304						switch (dataMediaSource) {
9305							case 'media-xl':
9306								return mediaThumbFixedHeight[0]
9307								break;
9308							case 'media-lg':
9309								return mediaThumbFixedHeight[1]
9310								break;
9311							case 'media-md':
9312								return mediaThumbFixedHeight[2]
9313								break;
9314							case 'media-sm':
9315								return mediaThumbFixedHeight[3]
9316								break;
9317							case 'media-xs':
9318								return mediaThumbFixedHeight[4]
9319								break;
9320						};
9321					};
9322					
9323					function checkInitThumbGap() {
9324						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9325					
9326						switch (dataMediaSource) {
9327							case 'media-xl':
9328								return mediaThumbGap[0]
9329								break;
9330							case 'media-lg':
9331								return mediaThumbGap[1]
9332								break;
9333							case 'media-md':
9334								return mediaThumbGap[2]
9335								break;
9336							case 'media-sm':
9337								return mediaThumbGap[3]
9338								break;
9339							case 'media-xs':
9340								return mediaThumbGap[4]
9341								break;
9342						};
9343					};
9344					function sliderPaginationChecking() {
9345						let sliderPaginationBlock = $this.find('.splide__custom__pagination');
9346						setTimeout(function() {
9347						if (sliderPaginationBlock.find('li').length == 1) {
9348							sliderPaginationBlock.hide();
9349						}
9350						 }, 200);
9351						
9352					};
9353	            }
9354	        });
9355	    }	
9356	};
9357	
9358	lpc_template.queue.sliderBlockThumbGallery = function ($self) {
9359	    var $block = $self.attr('data-slider-gallary-thumb-init') ? $self : $self.find('[data-slider-gallary-thumb-init]');
9360	    
9361	    if ($block.length) {
9362	        $block.each(function(){
9363	            let $this = $(this);
9364				let $alignItem = $this.find($this.data('align-item'));
9365				let mediaGap = $this.data('margin');
9366				let mediaPerPage = $(this).data('count');
9367				let mediaThumbGap = $this.data('thumb-margin');
9368				let mediaThumbFixedWidth = $this.data('thumb-width');
9369				let mediaThumbFixedHeight = $this.data('thumb-height');
9370				let mediaThumbDirectionItems = $this.data('thumb-direction');
9371				let mediaThumbDirection = [];
9372
9373				mediaThumbDirectionItems.forEach(function (item){
9374					if(item == 1) {
9375						item = 'ttb'
9376					}
9377					if(item == 0) {
9378						item = 'ltr'
9379					}
9380					mediaThumbDirection.push(item)
9381				});
9382	                
9383	            if($this.find('#main-slider').not('.is-active').length != 0 ) {
9384	                let splideThumbGallary = new Splide( $this.find('.splide').not('.is-active')[0], {
9385						autoplay: $this.data('autoplay'),
9386						speed: $this.data('speed'),
9387						interval: $this.data('pause'),
9388	                    rewind: $this.data('infinite'),
9389	                    lazyLoad: $this.data('lazy-load'),
9390	                    rewind: true,
9391	                    perMove: 1,
9392						perPage: checkInitPerPage(),
9393						dragMinThreshold: {
9394						    mouse: 5,
9395						    touch: 10,
9396						}	
9397	                });
9398	                
9399	                let thumbnailsGallary = new Splide($this.find('.thumbnail-slider').not('.is-active')[0], {
9400	                  direction       : checkInitThumbDirection(),
9401					  rewind          : true,
9402					  count			  : 6,
9403					  fixedWidth      : checkInitThumbWidth(),
9404					  fixedHeight     : checkInitThumbHeight(),
9405					  isNavigation    : true,
9406					  pagination      : false,
9407					  perPage		  : 6,
9408					  cover           : false,
9409					  arrows     	  : $this.data('thumb-arrow'),
9410                	  drag            : true,
9411                	  padding         : 4,
9412					  gap             : checkInitThumbGap(),
9413					  clones          : 5,
9414					  heightRatio     : $this.data('height'),
9415					  dragMinThreshold: {
9416					    mouse: 5,
9417					    touch: 10,
9418					  }	,
9419					  classes 		  : {
9420					  	arrows: "splide__arrows splide__custom__arrows"
9421					  }
9422					});
9423
9424	                splideThumbGallary.sync( thumbnailsGallary );
9425	                
9426	                splideThumbGallary.mount();
9427	                
9428            		thumbnailsGallary.mount();
9429                	
9430					sliderBreakPoints();
9431					
9432					sliderPaginationChecking();
9433					
9434					document.addEventListener('dataMediaSourceChange', sliderBreakPoints);
9435					
9436					function sliderBreakPoints() {
9437						
9438		                let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9439						setTimeout(function(){
9440							if ($alignItem.length) {
9441								let itemHeight = $alignItem.outerHeight() / 2;
9442								let arrowsPosition = itemHeight + $alignItem.position().top;
9443	
9444								$this.find('.splide__arrow').css('top', arrowsPosition);
9445							}
9446						}, 100);
9447						
9448		                switch (dataMediaSource) {
9449		                    case 'media-xl':
9450		                        splideThumbGallary.options = {
9451									arrows: true,
9452									pagination: true,
9453		                            gap: mediaGap[0],
9454		                            perPage: mediaPerPage[0],
9455		                            
9456		                        };
9457
9458		                        break;
9459		                    case 'media-lg':
9460		                        splideThumbGallary.options = {
9461									arrows: true,
9462									pagination: true,
9463		                            gap: mediaGap[1],
9464		                            perPage: mediaPerPage[1],
9465		                        };
9466		
9467		                        break;
9468		                    case 'media-md':
9469		                        splideThumbGallary.options = {
9470									arrows: true,
9471									pagination: true,
9472		                            gap: mediaGap[2],
9473		                            perPage: mediaPerPage[2],
9474		                        };
9475		                        break;
9476		                    case 'media-sm':
9477		                        splideThumbGallary.options = {
9478									arrows: false,
9479									pagination: true,
9480		                            gap: mediaGap[3],
9481		                            perPage: mediaPerPage[3],
9482		                        };
9483		
9484		                        break;
9485		                    case 'media-xs':
9486		                        splideThumbGallary.options = {
9487									arrows: false,
9488									pagination: true,
9489		                            gap: mediaGap[4],
9490		                            perPage: mediaPerPage[4],
9491		                        };
9492
9493		                        break;
9494		                }
9495		                if($block.data('slider-gallary-thumb-init') == true) {
9496							switch (dataMediaSource) {
9497			                    case 'media-xl':
9498			                        thumbnailsGallary.options = {
9499			                            gap: mediaThumbGap[0],
9500			                            fixedWidth: mediaThumbFixedWidth[0],
9501			                            fixedHeight: mediaThumbFixedHeight[0],
9502			                            direction: mediaThumbDirection[0],
9503		                        		heightRatio     : 3.2,
9504			                        };
9505			
9506			                        break;
9507			                    case 'media-lg':
9508			                        thumbnailsGallary.options = {
9509			                            gap: mediaThumbGap[1],
9510			                            fixedWidth: mediaThumbFixedWidth[1],
9511			                            fixedHeight: mediaThumbFixedHeight[1],
9512			                            direction: mediaThumbDirection[1],
9513			                            heightRatio     : 3.2,
9514			                        };
9515			
9516			                        break;
9517			                    case 'media-md':
9518			                        thumbnailsGallary.options = {
9519			                            gap: mediaThumbGap[2],
9520			                            fixedWidth: mediaThumbFixedWidth[2],
9521			                            fixedHeight: mediaThumbFixedHeight[2],
9522			                            direction: mediaThumbDirection[2],
9523			                            heightRatio     : 3.2,
9524			                        };
9525			
9526			                        break;
9527			                    case 'media-sm':
9528			                        thumbnailsGallary.options = {
9529			                            gap: mediaThumbGap[3],
9530			                            fixedWidth: mediaThumbFixedWidth[3],
9531			                            fixedHeight: mediaThumbFixedHeight[3],
9532			                            direction: mediaThumbDirection[3],
9533			                            heightRatio     : 3.2,
9534			                        };
9535			
9536			                        break;
9537			                    case 'media-xs':
9538			                        thumbnailsGallary.options = {
9539			                            gap: mediaThumbGap[4],
9540			                            fixedWidth: mediaThumbFixedWidth[4],
9541			                            fixedHeight: mediaThumbFixedHeight[4],
9542			                            direction: mediaThumbDirection[4],
9543			                            heightRatio     : 3.2,
9544			                        };
9545			                        
9546			                        break;
9547			                }
9548						}
9549					};
9550					
9551					function checkInitPerPage() {
9552						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9553					
9554						switch (dataMediaSource) {
9555							case 'media-xl':
9556								return mediaPerPage[0]
9557								break;
9558							case 'media-lg':
9559								return mediaPerPage[1]
9560								break;
9561							case 'media-md':
9562								return mediaPerPage[2]
9563								break;
9564							case 'media-sm':
9565								return mediaPerPage[3]
9566								break;
9567							case 'media-xs':
9568								return mediaPerPage[4]
9569								break;
9570						};
9571					};
9572					
9573					function checkInitThumbWidth() {
9574						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9575					
9576						switch (dataMediaSource) {
9577							case 'media-xl':
9578								return mediaThumbFixedWidth[0]
9579								break;
9580							case 'media-lg':
9581								return mediaThumbFixedWidth[1]
9582								break;
9583							case 'media-md':
9584								return mediaThumbFixedWidth[2]
9585								break;
9586							case 'media-sm':
9587								return mediaThumbFixedWidth[3]
9588								break;
9589							case 'media-xs':
9590								return mediaThumbFixedWidth[4]
9591								break;
9592						};
9593					};
9594					
9595					function checkInitThumbHeight() {
9596						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9597					
9598						switch (dataMediaSource) {
9599							case 'media-xl':
9600								return mediaThumbFixedHeight[0]
9601								break;
9602							case 'media-lg':
9603								return mediaThumbFixedHeight[1]
9604								break;
9605							case 'media-md':
9606								return mediaThumbFixedHeight[2]
9607								break;
9608							case 'media-sm':
9609								return mediaThumbFixedHeight[3]
9610								break;
9611							case 'media-xs':
9612								return mediaThumbFixedHeight[4]
9613								break;
9614						};
9615					};
9616					
9617					function checkInitThumbGap() {
9618						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9619					
9620						switch (dataMediaSource) {
9621							case 'media-xl':
9622								return mediaThumbGap[0]
9623								break;
9624							case 'media-lg':
9625								return mediaThumbGap[1]
9626								break;
9627							case 'media-md':
9628								return mediaThumbGap[2]
9629								break;
9630							case 'media-sm':
9631								return mediaThumbGap[3]
9632								break;
9633							case 'media-xs':
9634								return mediaThumbGap[4]
9635								break;
9636						};
9637					};
9638					
9639					function checkInitThumbDirection() {
9640						let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
9641					
9642						switch (dataMediaSource) {
9643							case 'media-xl':
9644								return mediaThumbDirection[0]
9645								break;
9646							case 'media-lg':
9647								return mediaThumbDirection[1]
9648								break;
9649							case 'media-md':
9650								return mediaThumbDirection[2]
9651								break;
9652							case 'media-sm':
9653								return mediaThumbDirection[3]
9654								break;
9655							case 'media-xs':
9656								return mediaThumbDirection[4]
9657								break;
9658						};
9659					};
9660					
9661					function sliderPaginationChecking() {
9662						let sliderPaginationBlock = $this.find('.splide__custom__pagination');
9663						
9664						setTimeout(function() {
9665						if (sliderPaginationBlock.find('li').length == 1) {
9666							sliderPaginationBlock.hide();
9667						}
9668						 }, 200);
9669						
9670					};
9671	            }
9672	        });
9673	    }	
9674	};
9675	
9676	
9677	lpc_template.queue.tabsBlocks = function($self) {
9678		var $block = $self.find('.lp-js-tabs');
9679		if ($block.length) {
9680			$block.each(function() {
9681				let $this = $(this);
9682				var $tab = $this.find(".lpc-tab-gallery__tab");
9683				var $tabs = $this.find(".lpc-tab-gallery__tabs");
9684				var $item = $this.find(".lpc-tab-gallery__image");
9685				
9686				if ($tabs.hasClass('_type-group') || $tabs.hasClass('_type-btn')) {
9687					$tab.first().find('.lp-button').addClass('lpc-button--type-1');
9688					$tab.first().find('.lp-button').removeClass('lpc-button--type-3');
9689					$tab.first().find('.lp-button').removeClass('lpc-button--type-2');
9690					
9691					setTimeout(function() { 
9692					let lpcButtonType1 = $this.find('.lpc-button--type-1'); // Ищем внутри текущего блока
9693        			let borderRadiusValue = lpcButtonType1.css('border-radius'); // Получаем border-radius
9694        
9695        			$('.lpc-tab-gallery__tabs._type-group').css('border-radius', borderRadiusValue); // Применяем border-radius только внутри этого блока
9696					}, 50);
9697				}
9698				$tab.first().addClass('active');
9699			    $item.first().addClass('active');
9700			
9701						
9702			    $tab.on('click', function () {
9703			        const index = $(this).index(); 
9704			
9705			        $tab.removeClass('active');
9706			        
9707			        $item.removeClass('active');
9708			
9709			        $(this).addClass('active');
9710			        $item.eq(index).addClass('active');
9711			        if ($(this).closest('._type-group').length){
9712			        	if ($(this).hasClass('active')) {
9713			        		$(this).find('.lp-button').removeClass('lpc-button--type-2', 'lpc-button--type-3');
9714			        		$(this).find('.lp-button').addClass('lpc-button--type-1');
9715			        		$(this).siblings('.lpc-tab-gallery__tab').find('.lp-button').removeClass('lpc-button--type-1');
9716			        		$(this).siblings('.lpc-tab-gallery__tab').find('.lp-button').addClass('lpc-button--type-2', 'lpc-button--type-3');
9717			        	}
9718			        }
9719			        if ($(this).closest('._type-btn').length){
9720			        	if ($(this).hasClass('active')) {
9721			        		$(this).find('.lp-button').removeClass('lpc-button--type-2');
9722			        		$(this).find('.lp-button').addClass('lpc-button--type-1');
9723			        		$(this).siblings('.lpc-tab-gallery__tab').find('.lp-button').removeClass('lpc-button--type-1');
9724			        		$(this).siblings('.lpc-tab-gallery__tab').find('.lp-button').addClass('lpc-button--type-2');
9725			        	}
9726			        }
9727				});
9728			});	
9729		}
9730	};
9731	
9732	
9733	lpc_template.queue.fixingPanelShow = function($self) {
9734		var $fixPanelBasis = $self.find('.lpc-block-fix-panel-basis');
9735		if($fixPanelBasis.length) {
9736			$fixPanelBasis.each(function(){
9737				var $fixPanel = $(this).closest('.lpc-block').find('.lpc-block-fix-panel');
9738				var $fixPanelWrap = $(this).closest('.lpc-block-fix-panel-wrap');
9739				
9740				function isElementInViewport($el) {
9741				    var rect = $el[0].getBoundingClientRect();
9742				    return (
9743				        rect.top >= 0 &&
9744				        rect.left >= 0 &&
9745				        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
9746				        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
9747				    );
9748				    
9749				}
9750				
9751				var $sectionTarget = $(this);
9752				
9753				if (isElementInViewport($sectionTarget)) {
9754					 $fixPanel.hide();
9755				}
9756				
9757				$fixPanelWrap.on("scroll", function () {
9758			        if (isElementInViewport($sectionTarget)) {
9759			            $fixPanel.hide();
9760			        } else {
9761			            $fixPanel.css("display", "flex");
9762			        }
9763			    });
9764			});
9765		}
9766	};
9767	
9768	lpc_template.queue.videoHoverPlay = function ($self) {
9769		const $blocks = $self.find('.lpc_hover_play_video');
9770		
9771		if (!$blocks.length) return;
9772	
9773		let hoverTimeout;
9774		let leaveTimeout;
9775	
9776		$blocks.off('mouseenter.videoHover mouseleave.videoHover');
9777	
9778		function setIframeAllowAutoplay($iframe) {
9779			try {
9780				const iframe = $iframe[0];
9781				if (!iframe) return;
9782				const allow = iframe.getAttribute('allow') || '';
9783				if (!/autoplay/.test(allow)) {
9784					iframe.setAttribute('allow', (allow + ' autoplay').trim());
9785				}
9786			} catch (e) {
9787				console.warn('setIframeAllowAutoplay error', e);
9788			}
9789		}
9790	
9791		function updateQueryParam(url, key, value) {
9792			try {
9793				const u = new URL(url, location.href);
9794				if (value === null) u.searchParams.delete(key);
9795				else u.searchParams.set(key, value);
9796				return u.toString();
9797			} catch (e) {
9798				if (url.indexOf('?') === -1) return url + '?' + key + '=' + value;
9799				if (new RegExp('([?&])' + key + '=').test(url)) {
9800					return url.replace(new RegExp('([?&])' + key + '=[^&]*'), '$1' + key + '=' + value);
9801				}
9802				return url + '&' + key + '=' + value;
9803			}
9804		}
9805	
9806		function getPlatformFromSrc(src) {
9807			if (!src) return null;
9808			if (src.includes('youtube.com') || src.includes('youtu.be')) return 'youtube';
9809			if (src.includes('vk.com')) return 'vk';
9810			if (src.includes('rutube.ru')) return 'rutube';
9811			if (src.includes('ok.ru') || src.includes('odnoklassniki')) return 'ok';
9812			if (src.includes('dzen.ru') || src.includes('zen.yandex')) return 'dzen';
9813			return null;
9814		}
9815	
9816		function sendCommandToIframe(iframe, platform, command) {
9817			try {
9818				if (!iframe || !iframe.contentWindow) return;
9819				if (platform === 'youtube') {
9820					iframe.contentWindow.postMessage(
9821						`{"event":"command","func":"${command === 'play' ? 'playVideo' : 'pauseVideo'}","args":""}`,
9822						'*'
9823					);
9824				} else if (platform === 'vk') {
9825					iframe.contentWindow.postMessage({ api: 1, method: command }, '*');
9826				} else if (platform === 'rutube') {
9827					iframe.contentWindow.postMessage({ type: command }, '*');
9828				} else if (platform === 'ok') {
9829					iframe.contentWindow.postMessage({ cmd: command }, '*');
9830				}
9831				// Dzen не поддерживает postMessage, поэтому управляем через src
9832			} catch (e) {
9833				console.warn('sendCommandToIframe error', e);
9834			}
9835		}
9836	
9837		function triggerPlay($container) {
9838			const $iframe = $container.find('iframe').first();
9839			const $video = $container.find('video').first();
9840	
9841			// --- Обычное видео ---
9842			if ($video.length) {
9843				const video = $video[0];
9844				video.muted = true;
9845				video.setAttribute('playsinline', '');
9846				video.play().catch(() => {});
9847				return;
9848			}
9849	
9850			// --- iframe ---
9851			if (!$iframe.length) return;
9852	
9853			const iframe = $iframe[0];
9854			setIframeAllowAutoplay($iframe);
9855	
9856			let src = iframe.getAttribute('src') || '';
9857			const platform = getPlatformFromSrc(src);
9858	
9859			if (platform === 'dzen') {
9860				src = updateQueryParam(src, 'autoplay', '1');
9861				src = updateQueryParam(src, 'mute', '1');
9862				iframe.setAttribute('src', src);
9863				console.log('Dzen autoplay forced:', src);
9864				return;
9865			}
9866	
9867			sendCommandToIframe(iframe, platform, 'play');
9868	
9869			if (!/autoplay=1/.test(src)) {
9870				src = updateQueryParam(src, 'autoplay', '1');
9871				src = updateQueryParam(src, 'mute', '1');
9872				iframe.setAttribute('src', src);
9873				console.log('iframe autoplay forced:', src);
9874			}
9875		}
9876	
9877		function triggerPause($container) {
9878			const $iframe = $container.find('iframe').first();
9879			const $video = $container.find('video').first();
9880	
9881			// --- Обычное видео ---
9882			if ($video.length) {
9883				const video = $video[0];
9884				video.pause();
9885				return;
9886			}
9887	
9888			// --- iframe ---
9889			if (!$iframe.length) return;
9890	
9891			const iframe = $iframe[0];
9892			let src = iframe.getAttribute('src') || '';
9893			const platform = getPlatformFromSrc(src);
9894	
9895			if (platform === 'dzen') {
9896				src = updateQueryParam(src, 'autoplay', '0');
9897				iframe.setAttribute('src', src);
9898				console.log('Dzen autoplay stopped:', src);
9899				return;
9900			}
9901	
9902			sendCommandToIframe(iframe, platform, 'pause');
9903	
9904			if (/autoplay=1/.test(src)) {
9905				src = updateQueryParam(src, 'autoplay', '0');
9906				iframe.setAttribute('src', src);
9907				console.log('iframe autoplay stopped:', src);
9908			}
9909		}
9910	
9911		/*$blocks.on('mouseenter.videoHover', function () {
9912			clearTimeout(leaveTimeout);
9913			const $this = $(this);
9914			hoverTimeout = setTimeout(() => {
9915				triggerPlay($this);
9916			}, 500);
9917		});
9918	
9919		$blocks.on('mouseleave.videoHover', function () {
9920			clearTimeout(hoverTimeout);
9921			const $this = $(this);
9922			leaveTimeout = setTimeout(() => {
9923				triggerPause($this);
9924			}, 500);
9925		});Старый*/
9926
9927		$blocks.on('mouseenter.videoHover', function () {
9928		    const $this = $(this);
9929		    
9930		    // Очищаем таймер ухода именно для ЭТОГО блока
9931		    clearTimeout($this.data('leaveTimeout'));
9932		    
9933		    const hTimeout = setTimeout(() => {
9934		        triggerPlay($this);
9935		    }, 50);
9936		    
9937		    // Сохраняем таймер наведения в этот блок
9938		    $this.data('hoverTimeout', hTimeout);
9939		});
9940		
9941		$blocks.on('mouseleave.videoHover', function () {
9942		    const $this = $(this);
9943		    
9944		    // Очищаем таймер наведения именно для ЭТОГО блока
9945		    clearTimeout($this.data('hoverTimeout'));
9946		    
9947		    const lTimeout = setTimeout(() => {
9948		        triggerPause($this);
9949		    }, 50);
9950		    
9951		    // Сохраняем таймер ухода в этот блок
9952		    $this.data('leaveTimeout', lTimeout);
9953		});
9954	};
9955	
9956	/*lpc_template.queue.videoPlayButtonDefolt = function($self) {
9957	    var $allVideoParents = $self.find('.js-lp-play-video').closest('.lp-video-block-wrappper');
9958	
9959	    $self.on('touchend click', '.js-lp-play-video', function(e) {
9960	        e.preventDefault();
9961	
9962	        var $this = $(this);
9963	        var thisVideo = $this.parent('.lp-video-block-wrappper').find('video')[0];
9964	
9965	        $this.addClass('hide');
9966	        thisVideo.setAttribute('controls', 1);
9967	        thisVideo.play();
9968	        
9969	    });
9970	    
9971	    $allVideoParents.find('video').each(function(){
9972			var $video = $(this);
9973			
9974			this.addEventListener('play', function() {
9975				$video.parent('.lp-video-block-wrappper').find('.js-lp-play-video').addClass('hide');
9976			});
9977			
9978			this.addEventListener('pause', function(){
9979				$video.parent('.lp-video-block-wrappper').find('.js-lp-play-video').removeClass('hide');
9980			});
9981		});
9982	};*/
9983	lpc_template.queue.videoPlayButtonDefolt = function($self) {
9984    // 1. Предварительная настройка всех видео для Android
9985    $self.find('.lp-video-block-wrappper video').each(function() {
9986        this.setAttribute('playsinline', '');
9987        this.setAttribute('webkit-playsinline', '');
9988        this.preload = "metadata"; // Важно для Android, чтобы плеер был готов
9989    });
9990
9991    // 2. Единый обработчик клика
9992    $self.on('click', '.js-lp-play-video', function(e) {
9993        e.preventDefault();
9994        e.stopPropagation();
9995
9996        var $btn = $(this);
9997        var $wrapper = $btn.closest('.lp-video-block-wrappper');
9998        var video = $wrapper.find('video')[0];
9999
10000        if (!video) return;
10001
10002        // Сначала запускаем видео, потом меняем классы (Android любит такой порядок)
10003        video.controls = true;
10004        
10005        var promise = video.play();
10006        
10007        if (promise !== undefined) {
10008            promise.then(function() {
10009                // Воспроизведение началось успешно
10010                $btn.addClass('hide');
10011            }).catch(function(error) {
10012                console.log("Android Autoplay Blocked: ", error);
10013                // Если заблокировано, пробуем запустить с выключенным звуком (последний шанс)
10014                video.muted = true;
10015                video.play();
10016                $btn.addClass('hide');
10017            });
10018        } else {
10019            // Для совсем старых браузеров без Promise
10020            $btn.addClass('hide');
10021        }
10022    });
10023
10024    // 3. Синхронизация состояния (если пользователь нажал на само видео)
10025    $self.find('.lp-video-block-wrappper video').on('play', function() {
10026        $(this).closest('.lp-video-block-wrappper').find('.js-lp-play-video').addClass('hide');
10027    }).on('pause ended', function() {
10028        $(this).closest('.lp-video-block-wrappper').find('.js-lp-play-video').removeClass('hide');
10029    });
10030};
10031	
10032	lpc_template.queue.videoPlayButton = function($self) {
10033	    let $block = $self.find('.lpc-play-video-init');
10034	    
10035	    if ($block.length) {
10036	        $block.each(function() {
10037	            let $this = $(this);
10038	            let $videoPlayButton = $this.find('.js-lp-play-video');
10039	            let $allVideoParets = $this.find('.lp-video-block-wrappper');
10040	            let thisVideo = $allVideoParets.find('video')[0];
10041	            	
10042	            function isMobile() {
10043	                return /Android|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i.test(navigator.userAgent) || window.innerWidth <= 768;
10044	            }
10045	
10046	            function togglePlayButton($video, show) {
10047	                let $button = $video.parent('.lp-video-block-wrappper').find('.js-lp-play-video');
10048	                if (show) {
10049	                    $button.removeClass('hide');
10050	                } else {
10051	                    $button.addClass('hide');
10052	                }
10053	            }
10054	                        
10055	            if (isMobile()) {
10056	                $videoPlayButton.addClass('hide');
10057	                if (thisVideo) {
10058	                    thisVideo.play();
10059	                    thisVideo.setAttribute('controls', 1);
10060	                }
10061	                return;
10062	            }
10063	            
10064	            $videoPlayButton.on('touchstart click', function(event) {
10065	                event.preventDefault();
10066	                let $this = $(this);
10067	
10068	                if (thisVideo) {
10069	                    $this.addClass('hide');
10070	                    thisVideo.play();
10071	                    thisVideo.setAttribute('controls', 1);
10072	                }
10073	            });
10074	
10075	            $allVideoParets.find('video').each(function() {
10076	                let $video = $(this);
10077	                
10078	                this.addEventListener('play', function() {
10079	                    togglePlayButton($video, false);
10080	                });
10081	        
10082	                this.addEventListener('pause', function() {
10083	                    togglePlayButton($video, true);
10084	                });
10085	            });
10086	        });
10087	    }
10088	};
10089
10090	lpc_template.queue.autoplayVideo = function ($self) {
10091    var $block = $self.find('[data-autoplay-video="1"]');
10092	
10093    if ($block.length) {
10094      $block.on("autoplayVideo", function (e, type, nodeName) {
10095        var video = this.querySelector(nodeName);
10096
10097        if (nodeName === "video") {
10098          if (type === "play") {
10099            video.play();
10100          } else {
10101            video.pause();
10102          }
10103        } else if (nodeName === "iframe") {
10104          var video = $(video).data("youtube");
10105
10106          if (type === "play") {
10107            video.playVideo();
10108          } else {
10109            video.pauseVideo();
10110          }
10111        }
10112      });
10113    }
10114
10115    //setTimeout(function(){
10116    //	$win.trigger('scroll');
10117    //}, 1000);
10118  };
10119  
10120  	lpc_template.queue.audioBlock = function ($self) {
10121	    var $block = $self.find('.lpc-audio');
10122	
10123	    let observer = new IntersectionObserver((entries, observer) => {
10124	        entries.forEach(entry => {
10125	            if (entry.isIntersecting) {
10126	                let $block = $(entry.target);
10127	                initAudioBlock($block);
10128	                observer.unobserve(entry.target); // Убираем наблюдение после инициализации
10129	            }
10130	        });
10131	    }, { threshold: 0.3 }); // Настроен на 30% видимости
10132	
10133	    $block.each(function () {
10134	        observer.observe(this);
10135	    });
10136	
10137	    
10138	    
10139	    function initAudioBlock($block) {
10140	    let audios = $block.find("audio");
10141	    let playPauseButtons = $block.find(".audio-play-pause");
10142	    let progressBars = $block.find(".audio-progress");
10143	    let timeDisplays = $block.find(".audio-time");
10144	    let volumeSliders = $block.find(".audio-volume");
10145	    let downloadButtons = $block.find(".audio-download");
10146	    let muteButtons = $block.find(".audio-muted");
10147	    let moreBtns = $block.find('.audio-more-btn');
10148	    let speedSelects = $block.find('.audio-speed-select');
10149	
10150	    playPauseButtons.each(function (index) {
10151	        let playPause = $(this);
10152	        let audio = audios[index];
10153	        let volumeSlider = volumeSliders.eq(index);
10154	        let downloadButton = downloadButtons.eq(index);
10155	        let muteButton = muteButtons.eq(index);
10156	        let moreBtn = moreBtns.eq(index);
10157	        let speedSelect = speedSelects.eq(index);
10158	        let progressBar = progressBars.eq(index);
10159	        let timeDisplay = timeDisplays.eq(index);
10160	
10161	        let computedColor = '#ffffff'; // fallback по умолчанию
10162	
10163	        setTimeout(() => {
10164	            let audioPlayer = playPause.closest('.audio-player')[0];
10165	            if (audioPlayer) {
10166	                computedColor = getComputedStyle(audioPlayer).color;
10167	            }
10168	
10169	            // Установка градиента громкости при инициализации
10170	            volumeSlider.css('background', `linear-gradient(to right, var(--primary-color-base) 100%, ${c
10170omputedColor} 100%)`);
10171	        }, 50);
10172	
10173	        let playIcon = '<svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10.6235 17.8087L17.5059 13.3848C17.8353 13.1724 18 12.8775 18 12.5C18 12.1225 17.8353 11.8276 17.5059 11.6152L10.6235 7.1913C10.2706 6.95536 9.91177 6.93767 9.54706 7.13822C9.18235 7.33877 9 7.65139 9 8.07609V16.9239C9 17.3486 9.18235 17.6612 9.54706 17.8618C9.91177 18.0623 10.2706 18.0446 10.6235 17.8087Z"/></svg>';
10174			let pauseIcon = '<svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M8 17C8 17.5523 8.44772 18 9 18H10C10.5523 18 11 17.5523 11 17V8C11 7.44771 10.5523 7 10 7H9C8.44772 7 8 7.44772 8 8V17ZM14 17C14 17.5523 14.4477 18 15 18H16C16.5523 18 17 17.5523 17 17V8C17 7.44771 16.5523 7 16 7H15C14.4477 7 14 7.44772 14 8V17Z" fill="#1F1F1F"/></svg>';
10175	
10176	        playPause.on("click", function () {
10177	            if (audio.paused) {
10178	                $("audio").each(function () { this.pause(); });
10179	                $(".audio-play-pause").html(playIcon);
10180	                audio.play();
10181	                playPause.html(pauseIcon);
10182	            } else {
10183	                audio.pause();
10184	                playPause.html(playIcon);
10185	            }
10186	        });
10187	
10188	        $(audio).on("timeupdate", function () {
10189	            if (isFinite(audio.duration)) {
10190	                let val = (audio.currentTime / audio.duration) * 100;
10191	                progressBar.val(val);
10192	                timeDisplay.text(formatTime(audio.currentTime));
10193	                progressBar.css('background', `linear-gradient(to right, var(--primary-color-base) ${val}%, ${computedColor} ${val}%)`);
10194	            }
10195	        });
10196	
10197	        progressBar.on("input", function () {
10198	            if (isFinite(audio.duration)) {
10199	                audio.currentTime = (progressBar.val() / 100) * audio.duration;
10200	            }
10201	        });
10202	
10203	        volumeSlider.on("input", function () {
10204	            audio.volume = volumeSlider.val();
10205	            let valVol = audio.volume * 100;
10206	            volumeSlider.css('background', `linear-gradient(to right, var(--primary-color-base) ${valVol}%, ${computedColor} ${valVol}%)`);
10207	
10208	            if (audio.volume == 0) {
10209	                muteButton.addClass('mute');
10210	            } else {
10211	                muteButton.removeClass('mute');
10212	            }
10213	
10214	            if (audio.muted) audio.muted = false;
10215	        });
10216	
10217	        downloadButton.on("click", function () {
10218	            let audioSrc = $(audio).attr("src");
10219	            let link = document.createElement("a");
10220	            link.href = audioSrc;
10221	            link.download = audioSrc.split("/").pop();
10222	            document.body.appendChild(link);
10223	            link.click();
10224	            document.body.removeChild(link);
10225	        });
10226	        
10227	        
10228	        muteButton.on("click", function () {
10229	            $(this).toggleClass('mute');
10230	            audio.muted = !audio.muted;
10231	
10232	            if (audio.muted) {
10233	                volumeSlider.val(0);
10234	                volumeSlider.css('background', `linear-gradient(to right, var(--primary-color-base) 0%, ${computedColor} 0%)`);
10235	            } else {
10236	                let vol = audio.volume || 1;
10237	                let volVal = vol * 100;
10238	                volumeSlider.val(vol);
10239	                volumeSlider.css('background', `linear-gradient(to right, var(--primary-color-base) ${volVal}%, ${computedColor} ${volVal}%)`);
10240	            }
10241	        });
10242	
10243	        moreBtn.on('click', function () {
10244	        	$(".audio-more-dropdown").hide().find('.audio-speed-select').removeClass('_open');
10245	            $(this).siblings('.audio-more-dropdown').show().css({  "transform": "translate(0px, 0px)",  "opacity": "1"});
10246	        });
10247	
10248	        $(document).on("click", ".audio-speed-control", function () {
10249	            $(this).find(".audio-speed-select").addClass('_open');
10250	        });
10251	
10252	        $(document).on("click", function (e) {
10253	            if (!$(e.target).closest('.audio-more-dropdown').length && !$(e.target).closest('.audio-more-btn').length) {
10254	                $(".audio-more-dropdown").hide().find('.audio-speed-select').removeClass('_open');
10255	            }
10256	        });
10257	
10258	        speedSelect.on('change', function () {
10259	            let speed = parseFloat($(this).val());
10260	            if (audio) audio.playbackRate = speed;
10261	        });
10262	
10263	        function formatTime(seconds) {
10264	            let min = Math.floor(seconds / 60);
10265	            let sec = Math.floor(seconds % 60).toString().padStart(2, "0");
10266	            return `${min}:${sec}`;
10267	        }
10268	    });
10269	}
10270	};
10271	
10272	lpc_template.queue.lgNew = function($self) {
10273	    let $block = $self.find('.js-new-lg-init');
10274
10275	    if ($block.length) {
10276	        $block.each(function() {
10277	            let $block = $(this);
10278	            let lgCounter = $block.data('lg-counter');
10279	            let lgThumbnail = $block.data('lg-thumbnail');
10280	            
10281				//setTimeout(function() {
10282					lightGallery($block[0], {
10283		                plugins: [Zoom, Thumbnail, Video],
10284		                counter: lgCounter,
10285		                thumbnail: lgThumbnail,
10286		                selector: '.lpc-lg-item',
10287		                download: false,
10288		                mobileSettings: {
10289		                    preload: 2,
10290		                    controls: false,
10291		                    showCloseIcon: true
10292		                }
10293		            });
10294				//}, 2000);
10295	            
10296	            $block.find('.lpc-lg-item').removeClass('lpc_lg_pointer_events');
10297	        });
10298	    }
10299	}; 
10300
10301	lpc_template.queue.lg = function ($self) {
10302    var $block = $self.find(".js-lg-init");
10303
10304    if ($block.length) {
10305      //setTimeout(function () {
10306        $block.lightGallery({
10307          selector: ".lg-item",
10308          toogleThumb: false,
10309          getCaptionFromTitleOrAlt: false,
10310          download: false,
10311          thumbWidth: 64,
10312          thumbHeight: "64px",
10313          addClass: "_lpc-lg",
10314          nextHtml:
10315            '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M8.98528 4.32805C9.3758 3.93753 10.009 3.93753 10.3995 4.32805L17.0563 10.9849C17.4469 11.3754 17.4469 12.0086 17.0563 12.3991L10.3995 19.056C10.009 19.4465 9.3758 19.4465 8.98528 19.056C8.59475 18.6654 8.59475 18.0323 8.98528 17.6418L14.935 11.692L8.98528 5.74226C8.59475 5.35174 8.59475 4.71857 8.98528 4.32805Z" fill="white"/></svg>',
10316          prevHtml:
10317            '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M14.8492 5.03516L8.19239 11.692L14.8492 18.3489" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
10318        });
10319        
10320        $block.find('.lg-item').removeClass('lpc_lg_pointer_events');
10321        
10322      //}, 500);
10323    }
10324  };
10325  
10326  
10327  	// ================================= НЕ УДАЛЯТЬ! Тестовый код ================================= //
10328  	
10329  	// Заголовки для LPCv4 для медиа-запросов
10330	lpc_template.queue.adaptiveTitle = function ($self) {
10331	    let $block = $self.find('.adaptive_text_init');
10332	
10333	    if ($block.length) {
10334	
10335	        // Объект для хранения состояния фиксации размеров шрифтов для каждого заголовка и разрешения
10336	        let fixedSizes = {
10337	            'media-lg': {},
10338	            'media-md': {},
10339	            'media-sm': {},
10340	            'media-xs': {}
10341	        };
10342	
10343	        $block.each(function() {
10344	            $(this).find('.font-size-input').each(function() {
10345	                const media = $(this).data('media');
10346	                const heading = $(this).data('title'); // Заголовки (h1, h2, ..., h6)
10347	                const fontSize = parseFloat($(this).val());
10348	                const textElement = $self.find(`.lpc-adaptive-text__box[data-media="${media}"] .lpc-adaptive-text__title[data-title="${heading}"]`);
10349	
10350	                // Установка начального размера шрифта
10351	                textElement.css('fontSize', `${fontSize}px`);
10352	
10353	                $(this).on('input', function() {
10354	                    let newFontSize = parseFloat($(this).val());
10355	
10356	                    if (newFontSize < 0 || isNaN(newFontSize)) {
10357	                        newFontSize = Math.abs(newFontSize) || 0;
10358	                        $(this).val(newFontSize);
10359	                    }
10360	
10361	                    if (!isNaN(newFontSize)) {
10362	                        newFontSize = Math.round(newFontSize);
10363	                    }
10364	
10365	                    if (media === 'media-xl') {
10366	
10367	                        // Диапазоны для других разрешений
10368	                        const sizeLimits = {
10369	                            'h1': {
10370	                                'media-lg': { min: 34, max: 68 },
10371	                                'media-md': { min: 32, max: 64 },
10372	                                'media-sm': { min: 30, max: 60 },
10373	                                'media-xs': { min: 28, max: 56 }
10374	                            },
10375	                            'h2': {
10376	                                'media-lg': { min: 32, max: 62 },
10377	                                'media-md': { min: 30, max: 58 },
10378	                                'media-sm': { min: 28, max: 54 },
10379	                                'media-xs': { min: 26, max: 50 }
10380	                            },
10381	                            'h3': {
10382	                                'media-lg': { min: 30, max: 56 },
10383	                                'media-md': { min: 28, max: 52 },
10384	                                'media-sm': { min: 26, max: 48 },
10385	                                'media-xs': { min: 24, max: 44 }
10386	                            },
10387	                            'h4': {
10388	                                'media-lg': { min: 28, max: 50 },
10389	                                'media-md': { min: 26, max: 46 },
10390	                                'media-sm': { min: 24, max: 42 },
10391	                                'media-xs': { min: 22, max: 38 }
10392	                            },
10393	                            'h5': {
10394	                                'media-lg': { min: 26, max: 44 },
10395	                                'media-md': { min: 24, max: 40 },
10396	                                'media-sm': { min: 22, max: 36 },
10397	                                'media-xs': { min: 20, max: 32 }
10398	                            },
10399	                            'h6': {
10400	                                'media-lg': { min: 24, max: 40 },
10401	                                'media-md': { min: 22, max: 36 },
10402	                                'media-sm': { min: 20, max: 32 },
10403	                                'media-xs': { min: 18, max: 28 }
10404	                            }
10405	                        };
10406							
10407	                        // Адаптация размеров для других медиа-устройств
10408	                        const sizeRatios = {
10409	                            'media-lg': 0.9,
10410	                            'media-md': 0.9,
10411	                            'media-sm': 0.75,
10412	                            'media-xs': 0.65
10413	                        };
10414	
10415	                        $self.find('.font-size-input').each(function() {
10416	                            const otherMedia = $(this).data('media');
10417	                            const otherHeading = $(this).data('title');
10418	                            const otherTextElement = $self.find(`.lpc-adaptive-text__box[data-media="${otherMedia}"] .lpc-adaptive-text__title[data-title="${otherHeading}"]`);
10419	
10420	                            if (otherHeading === heading && (otherMedia === 'media-xl' || !fixedSizes[otherMedia][heading])) {
10421	                                let adaptedSize = otherMedia === 'media-xl' ? newFontSize : Math.round(newFontSize * sizeRatios[otherMedia]);
10422	
10423	                                // Применение ограничений для других медиа-устройств
10424	                                if (sizeLimits[heading] && sizeLimits[heading][otherMedia]) {
10425	                                    const { min, max } = sizeLimits[heading][otherMedia];
10426	                                    adaptedSize = Math.min(Math.max(adaptedSize, min), max);
10427	                                }
10428	
10429	                                $(this).val(adaptedSize);
10430	                                otherTextElement.css('fontSize', `${adaptedSize}px`);
10431	                                $(this).css('color', 'green');
10432	                            }
10433	                        });
10434	
10435	                    } else {
10436	                        fixedSizes[media][heading] = true;
10437	                        textElement.css('fontSize', `${newFontSize}px`);
10438	                        $(this).css('color', 'red');
10439	                        $(this).val(newFontSize);
10440	                    }
10441	                });
10442	            });
10443	        });
10444	    }
10445	};
10446	
10447	// Заголовки для LP для ширины сайта
10448	lpc_template.queue.adaptiveTitleContent = function ($self) {
10449	    let $block = $self.find('.adaptive_width_init');
10450	
10451	    if ($block.length) {
10452	        const sizeRatios = {
10453	            'h1': 1,
10454	            'h2': 0.9,
10455	            'h3': 0.8,
10456	            'h4': 0.7,
10457	            'h5': 0.6,
10458	            'h6': 0.5
10459	        };
10460	       
10461	        const sizeLimits = {
10462	            'h2': {
10463	                'media-xl': { min: 34, max: 66 },
10464	                'media-lg': { min: 32, max: 62 },
10465	                'media-md': { min: 30, max: 58 },
10466	                'media-sm': { min: 28, max: 54 },
10467	                'media-xs': { min: 26, max: 50 }
10468	            },
10469	            'h3': {
10470	                'media-xl': { min: 32, max: 60 },
10471	                'media-lg': { min: 30, max: 56 },
10472	                'media-md': { min: 28, max: 52 },
10473	                'media-sm': { min: 26, max: 48 },
10474	                'media-xs': { min: 24, max: 44 }
10475	            },
10476	            'h4': {
10477	                'media-xl': { min: 30, max: 54 },
10478	                'media-lg': { min: 28, max: 50 },
10479	                'media-md': { min: 26, max: 46 },
10480	                'media-sm': { min: 24, max: 42 },
10481	                'media-xs': { min: 22, max: 38 }
10482	            },
10483	            'h5': {
10484	                'media-xl': { min: 28, max: 48 },
10485	                'media-lg': { min: 26, max: 44 },
10486	                'media-md': { min: 24, max: 40 },
10487	                'media-sm': { min: 22, max: 36 },
10488	                'media-xs': { min: 20, max: 32 }
10489	            },
10490	            'h6': {
10491	                'media-xl': { min: 26, max: 44 },
10492	                'media-lg': { min: 24, max: 40 },
10493	                'media-md': { min: 22, max: 36 },
10494	                'media-sm': { min: 20, max: 32 },
10495	                'media-xs': { min: 18, max: 28 }
10496	            }
10497	        };
10498	
10499	        $block.each(function() {
10500	            $(this).find('.font-size-input').each(function() {
10501	                const media = $(this).data('media');
10502	                const heading = $(this).data('title'); // Заголовки (h1, h2, ..., h6)
10503	                const fontSize = parseFloat($(this).val());
10504	                const textElement = $self.find(`.lpc-adap-title-bl__container[data-media="${media}"] .lpc-title-js[data-title="${heading}"]`);
10505	
10506	                // Установка начального размера шрифта
10507	                textElement.css('fontSize', `${fontSize}px`);
10508	
10509	                $(this).on('input', function() {
10510	                    let newFontSize = parseFloat($(this).val());
10511	
10512	                    if (newFontSize < 0 || isNaN(newFontSize)) {
10513	                        newFontSize = Math.abs(newFontSize) || 0;
10514	                        $(this).val(newFontSize);
10515	                    }
10516	
10517	                    if (!isNaN(newFontSize)) {
10518	                        newFontSize = Math.round(newFontSize);
10519	                    }
10520	                   
10521	                    if (heading === 'h1') {
10522	                        $self.find(`.font-size-input[data-media="${media}"]`).each(function() {
10523	                            const otherHeading = $(this).data('title');
10524	                            const otherTextElement = $self.find(`.lpc-adap-title-bl__container[data-media="${media}"] .lpc-title-js[data-title="${otherHeading}"]`);
10525	
10526	                            // Рассчитываем размер шрифта на основе соотношения
10527	                            let adjustedSize = Math.round(newFontSize * sizeRatios[otherHeading]);
10528	
10529	                            // Применение ограничений для размера шрифта
10530	                            if (sizeLimits[otherHeading] && sizeLimits[otherHeading][media]) {
10531	                                const { min, max } = sizeLimits[otherHeading][media];
10532	                                adjustedSize = Math.min(Math.max(adjustedSize, min), max);
10533	                            }
10534	
10535	                            $(this).val(adjustedSize);
10536	                            otherTextElement.css('fontSize', `${adju
10536stedSize}px`);
10537	                            $(this).css('color', 'green');
10538	                        });
10539	                    } else {
10540	                        textElement.css('fontSize', `${newFontSize}px`);
10541	                        $(this).css('color', 'red');
10542	                    }
10543	                });
10544	            });
10545	        });
10546	    }
10547	};
10548	
10549	lpc_template.queue.adaptiveTexeContent = function ($self) {
10550	    let $block = $self.find('.adaptive_text_width_init');
10551	
10552	    if ($block.length) {
10553	    	
10554	        const sizeRatios = {
10555	            'p1': 1,
10556	            'p2': 0.95,
10557	            'p3': 0.9,
10558	            'p4': 0.85,
10559	        };
10560	
10561	       
10562	        const sizeLimits = {
10563	            'p2': {
10564	                'media-xl': { min: 20, max: 22 },
10565	                'media-lg': { min: 20, max: 22 },
10566	                'media-md': { min: 18, max: 20 },
10567	                'media-sm': { min: 18, max: 20 },
10568	                'media-xs': { min: 16, max: 18 }
10569	            },
10570	            'p3': {
10571	                'media-xl': { min: 18, max: 20 },
10572	                'media-lg': { min: 18, max: 20 },
10573	                'media-md': { min: 16, max: 18 },
10574	                'media-sm': { min: 16, max: 18 },
10575	                'media-xs': { min: 15, max: 16 }
10576	            },
10577	            'p4': { 
10578	                'media-xl': { min: 16, max: 18 },
10579	                'media-lg': { min: 16, max: 18 },
10580	                'media-md': { min: 16, max: 16 },
10581	                'media-sm': { min: 14, max: 16 },
10582	                'media-xs': { min: 14, max: 14 }
10583	            }
10584	        };
10585	
10586	        $block.each(function() {
10587	            $(this).find('.font-size-input').each(function() {
10588	                const media = $(this).data('media');
10589	                const heading = $(this).data('text'); // Заголовки (p1, p2, ..., h4)
10590	                const fontSize = parseFloat($(this).val());
10591	                const textElement = $self.find(`.lpc-adap-text-bl__container[data-media="${media}"] .lpc-text-js[data-text="${heading}"]`);
10592	
10593	                
10594	                textElement.css('fontSize', `${fontSize}px`);
10595	
10596	                $(this).on('input', function() {
10597	                    let newFontSize = parseFloat($(this).val());
10598	
10599	                    if (newFontSize < 0 || isNaN(newFontSize)) {
10600	                        newFontSize = Math.abs(newFontSize) || 0;
10601	                        $(this).val(newFontSize);
10602	                    }
10603	
10604	                    if (!isNaN(newFontSize)) {
10605	                        newFontSize = Math.round(newFontSize);
10606	                    }
10607	
10608	                    
10609	                    if (heading === 'p1') {
10610	                       
10611	                        $self.find(`.font-size-input[data-media="${media}"]`).each(function() {
10612	                            const otherHeading = $(this).data('text');
10613	                            const otherTextElement = $self.find(`.lpc-adap-text-bl__container[data-media="${media}"] .lpc-text-js[data-text="${otherHeading}"]`);
10614	
10615	                            
10616	                            let adjustedSize = Math.round(newFontSize * sizeRatios[otherHeading]);
10617	
10618	                            
10619	                            if (sizeLimits[otherHeading] && sizeLimits[otherHeading][media]) {
10620	                                const { min, max } = sizeLimits[otherHeading][media];
10621	                                adjustedSize = Math.min(Math.max(adjustedSize, min), max);
10622	                            }
10623	
10624	                            $(this).val(adjustedSize);
10625	                            otherTextElement.css('fontSize', `${adju
10625stedSize}px`);
10626	                            $(this).css('color', 'green');
10627	                        });
10628	                    } else {
10629	                        
10630	                        textElement.css('fontSize', `${newFontSize}px`);
10631	                        $(this).css('color', 'red');
10632	                    }
10633	                });
10634	            });
10635	        });
10636	    }
10637	};
10638	
10639	lpc_template.queue.tabsInitTest = function ($self) {
10640	    let $block = $self.find('.adaptive_width_init');
10641	
10642	    if ($block.length) {
10643	        $block.each(function() {
10644	            let $this = $(this);
10645	            let $button = $this.find('.lp-button');
10646	            let $tab = $this.find('.tab');
10647	            
10648	            $button.click(function() {
10649	                $button.removeClass('active');
10650	                $tab.removeClass('active');
10651	                
10652	                $(this).addClass('active'); 
10653	                $('#' + $(this).data('tab')).addClass('active'); 
10654	            });
10655	        });
10656	    }
10657	};
10658	// ================================= НЕ УДАЛЯТЬ! Тестовый код ================================= //
10659	
10660	
10661	lpc_template.queue.lpcContact2 = function ($blocks) {
10662	    var $block = $blocks.find(".lpc-contact-2");
10663	    let dataMediaSource = document.querySelector('.decor-wrap').dataset.mediaSource;
10664	    
10665	    if ($block.length && (dataMediaSource != 'media-sm' && dataMediaSource != 'media-xs')) {
10666	    	$block.each(function(){
10667	    		var $this = $(this),
10668	    		lpcMapBlockHeight = $this.find('.lpc-contact-2__content').height(),
10669				lpcMapBlock = $this.find('.lpc-contact-2__map-wrap');
10670				
10671		    	setTimeout(function() {
10672					lpcMapBlock.css('max-height', lpcMapBlockHeight)
10673		    	}, 1000);
10674	    	});
10675	    	
10676    	}
10677  	};
10678  	
10679  	lpc_template.queue.lpcConstructorFrameSelection = function ($blocks) {
10680  		if(window.location.pathname == "/my/s3/cms/v1/lp/live.edit.php") {
10681  			$('.content-lp-wrapper').addClass("lpc-const-frame-selection");
10682  		}
10683  		/*if(window.location.host == "mf1.ravshan95.oml.ru") {
10684  			$('.content-lp-wrapper').addClass("lpc-const-frame-selection-fix");
10685  		}*/
10686  	};
10687  	
10688  	lpc_template.queue.lpcForm5 = function ($blocks) {
10689	    var $block = $blocks.find(".lpc-form-5");
10690	    
10691	  	if ($block.length) {
10692	  		if($block.find("textarea").length != 0) {
10693	  		document.querySelector('.lpc-form-5 textarea').addEventListener('input', function (e) {
10694	  			
10695			  e.target.style.height = 50 + "px";
10696			  e.target.style.height = e.target.scrollHeight + 2 + "px"
10697			});
10698	    	
10699	  		}
10700	  	}
10701  	};
10702  	
10703  	lpc_template.queue.lpStepForm = function($self) {
10704	  var $block = $self.find('.js-lp-steps-form');
10705	
10706	  if ($block.length) {
10707	    $block.formsteps();
10708	  }
10709	};
10710
10711  lpc_template.checkAutoplayVideo = function ($blocks) {
10712    $blocks.each(function () {
10713      var $this = $(this),
10714        playStatus = $this.data("playStatus"),
10715        inViewport = isElementInViewport(this),
10716        $video = $this.find("video"),
10717        $thisVideo = $video.length ? $video : $this.find("iframe");
10718
10719      if (inViewport && playStatus !== "play") {
10720        $this.trigger("autoplayVideo", [
10721          "play",
10722          $thisVideo[0].nodeName.toLowerCase(),
10723        ]);
10724        $this.data("playStatus", "play");
10725      } else if (!inViewport && playStatus === "play") {
10726        $this.trigger("autoplayVideo", [
10727          "pause",
10728          $thisVideo[0].nodeName.toLowerCase(),
10729        ]);
10730        $this.data("playStatus", "pause");
10731      }
10732    });
10733  };
10734  
10735
10736  window.lp_init = function ($block) {
10737  	
10738  	if (typeof ReactLPConstructor == 'object') {
10739	    s3LP.is_cms = true;
10740	} // чтобы флаг заработал в новом конструкторе
10741	
10742	
10743	var initializedMaps = [];
10744
10745	var $maps = $block.find('.js-lpc-simple-map');
10746	
10747	if ($maps.length) {
10748	    $maps.each(function() {
10749	        var mapElement = this;
10750	        var id = $(mapElement).attr('id');
10751	
10752	        if (initializedMaps.includes(id)) return; 
10753	
10754	        var observer = new IntersectionObserver(function(entries, observerInstance) {
10755	            entries.forEach(function(entry) {
10756	                if (entry.isIntersecting) {
10757	                	
10758	                    lpc_template.initMaps($(mapElement)); 
10759	                    initializedMaps.push(id); 
10760	                    observerInstance.unobserve(entry.target);
10761	                }
10762	            });
10763	        }, {
10764	            root: null,
10765	            rootMargin: '0px',
10766	            threshold: 0.1
10767	        });
10768	
10769	        observer.observe(mapElement);
10770	    });
10771	}
10772
10773    /*var $maps = $block.find(".js-lpc-simple-map");
10774
10775    if ($maps.length) {
10776      setTimeout(function () {
10777        lpc_template.checkMapInitialization($maps);
10778      }, 250);
10779      $win.on("scroll", function () {
10780        lpc_template.checkMapInitialization($maps);
10781      });
10782      
10783    }*/
10784
10785    if (s3LP.is_cms) {
10786      var contentColor = $("#lpc_contructor_iframe")
10787        .contents()
10788        .find(".decor-wrap")
10789        .css("color");
10790      $("#landing_page_site").css("color", contentColor);
10791    }
10792
10793    $win
10794      .on("resize", function () {
10795        var decorWidth = $(".decor-wrap").width();
10796        $(".lpc-block:not(.custom-lpc-block)").css("max-width", decorWidth);
10797      })
10798      .trigger("resize");
10799
10800    Object.keys(lpc_template.queue).forEach(function (func) {
10801      var thisFunction = lpc_template.queue[func];
10802      if (typeof thisFunction == "function") {
10803        thisFunction($block);
10804      }
10805    });
10806
10807    var $autoplayVideo = $doc.find('[data-autoplay-video="1"]');
10808
10809    if ($autoplayVideo.length && !s3LP.is_cms && window.self == window.top) {
10810      $win.on("scroll", function () {
10811        lpc_template.checkAutoplayVideo($autoplayVideo);
10812      });
10813    }
10814    
10815    
10816
10817    let timeout;
10818
10819    $win
10820      .on("resize", function () {
10821
10822        clearTimeout(timeout)
10823
10824        timeout = setTimeout(function(){
10825          lpc_template.adaptiveBlock();
10826          lpc_template.popupAdaptiveBlock();
10827        }, 80);
10828
10829        $(".js-proportion-height").each(function () {
10830          var $this = $(this);
10831
10832          setProportionHeight($this, $this.data("proportion") || 100);
10833        });
10834      })
10835      .trigger("resize");
10836
10837    if (s3LP.is_cms && typeof LpController !== 'undefined') {
10838      LpController.convertImages($block);
10839
10840      setTimeout(function () {
10841        LpController.convertImages($block);
10842        LpController.afterSave(function () {
10843          $(".lpc-features-3-chart-item__number").each(function () {
10844            var $this = $(this);
10845            $this
10846              .closest(".lpc-features-3-chart-item")
10847              .find(".lpc-features-3-chart-item__bar-inner")
10848              .css("width", $this.text());
10849          });
10850        });
10851      }, 1000);
10852    }
10853
10854    if (document.location.hash.length > 1 && $(document.location.hash).length) {
10855      setTimeout(function () {
10856        $("html, body").scrollTop($(document.location.hash).offset().top);
10857      }, 200);
10858    }
10859    
10860    
10861    document.dispatchEvent(new Event('lpc_init_after', {bubbles: true}));
10862  };
10863
10864  window.onYouTubeIframeAPIReady = function () {
10865    $(function () {
10866      var listYoutube = $(".js-lp-video-youtube");
10867
10868      listYoutube.each(function () {
10869        var $this = $(this),
10870          isFullFrame = $this.hasClass("_not-paused");
10871
10872        var player = new YT.Player(this.id, {
10873          iv_load_policy: 3,
10874          modestbranding: 1,
10875          rel: 0,
10876          mute: isFullFrame ? 1 : 0,
10877          playsinline: 1,
10878          showinfo: isFullFrame ? 0 : 1,
10879          events: {
10880            onStateChange: function (event) {
10881              if (
10882                event.data == YT.PlayerState.ENDED &&
10883                $(event.target.a).hasClass("_not-paused")
10884              ) {
10885                event.target.playVideo();
10886              }
10887            },
10888          },
10889        });
10890
10891        $this.data("youtube", player);
10892      });
10893    });
10894  };
10895
10896  function isElementInViewport(el) {
10897    var rect = el.getBoundingClientRect();
10898    return rect.top <= window.innerHeight - 200 && rect.bottom >= 50;
10899  }
10900
10901  function setProportionHeight($block, proportion) {
10902    $block.height(($block.width() * proportion) / 100);
10903  }
10904  
10905	function s3PreloaderMutation(target) {
10906		const config = {
10907			attributes: true
10908		};
10909	
10910		const callback = function (mutationsList, observer) {
10911			for (let mutation of mutationsList) {
10912				if ($(target).find('.s3-preloader').hasClass('s3-preloader-hide') || $(target).hasClass('s3-preloader-hide')) {
10913					document.dispatchEvent(new Event('lpcLoadingDone', {bubbles: true}));
10914				}
10915			}
10916		};
10917	
10918		const observer = new MutationObserver(callback);
10919		observer.observe(target, config);
10920	};
10921
10922})();
10923
10924
10925document.addEventListener('lpc_init_after', function () { // вместо  DOMContentLoaded используем lpc_init_after чтобы работало в новом конструкторе, так как там нет события DOMContentLoaded
10926    if (!s3LP.is_cms) {
10927        // Храним уникальные ключи отправленных целей, чтобы не отправлять их повторно
10928        const sentGoals = new Set();
10929
10930        function sendBlockGoals(block, eventType) {
10931            // Определяем соответствия: атрибут → система
10932            const systems = [
10933                { attr: 'data-goal-metrika', system: 'metrika' },
10934                { attr: 'data-goal-sber', system: 'sber_ads' },
10935                { attr: 'data-goal-analytics', system: 'analytics' }
10936            ];
10937
10938            systems.forEach(({ attr, system }) => {
10939                const label = block.getAttribute(attr);
10940                if (label) {
10941                    // Формируем уникальный ключ, чтобы предотвратить повторную отправку
10942                    const key = `${system}_${label}_${eventType}`;
10943                    if (!sentGoals.has(key)) {
10944                        // Для sber_ads проверяем наличие счетчика, чтобы избежать ошибки
10945                        if (system === 'sber_ads') {
10946                            if (!s3.Goal.sberADSCounters || !s3.Goal.sberADSCounters[0]) {
10947                                console.warn("SberAds counter not available. Skipping sber_ads goal.");
10948                                return;
10949                            }
10950                        }
10951                        sentGoals.add(key);
10952                        s3.Goal.send({
10953                            system: system,
10954                            object: 'block',    // можно изменить тип объекта при необходимости
10955                            event: eventType,   // 'view' или 'anchor'
10956                            label: label
10957                        });
10958                    }
10959                }
10960            });
10961        }
10962
10963        /**
10964         * Наблюдение за блоками, имеющими хотя бы один из data-атрибутов цели.
10965         * При появлении блока в зоне видимости (50%) вызывается отправка события 'view',
10966         * если для блока ранее не было отправлено событие 'anchor'.
10967         */
10968        function observeBlocks() {
10969            const blocks = document.querySelectorAll('[data-goal-metrika], [data-goal-sber], [data-goal-analytics]');
10970            const observer = new IntersectionObserver((entries) => {
10971                entries.forEach((entry) => {
10972                    if (entry.isIntersecting) {
10973                        // Если для блока уже отправлено событие 'anchor', не отправляем 'view'
10974                        if (entry.target.dataset.goalAnchorSent !== "true") {
10975                            sendBlockGoals(entry.target, 'view');
10976                        }
10977                        observer.unobserve(entry.target); // прекращаем наблюдение после отправки
10978                    }
10979                });
10980            }, { threshold: 0.5 });
10981
10982            blocks.forEach((block) => observer.observe(block));
10983        }
10984
10985        /**
10986         * Обработка кликов по якорным ссылкам.
10987         * Если целевой блок имеет цели, отправляем их с типом 'anchor'.
10988         */
10989        function trackAnchorClicks() {
10990            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
10991                anchor.addEventListener('click', function () {
10992                    const targetId = this.getAttribute('href').substring(1);
10993                    const targetBlock = document.getElementById(targetId);
10994                    if (targetBlock) {
10995                        sendBlockGoals(targetBlock, 'anchor');
10996                        // Отмечаем, что для этого блока уже отправлено событие 'anchor'
10997                        targetBlock.dataset.goalAnchorSent = "true";
10998                    }
10999                });
11000            });
11001        }
11002
11003        // Если страница открыта с якорем, сразу отправляем событие 'anchor' для соответствующего блока
11004        if (window.location.hash) {
11005            const targetId = window.location.hash.substring(1);
11006            const targetBlock = document.getElementById(targetId);
11007            if (targetBlock) {
11008                sendBlockGoals(targetBlock, 'anchor');
11009                targetBlock.dataset.goalAnchorSent = "true";
11010            }
11011        }
11012
11013        // Инициализируем наблюдение за блоками и обработку якорных ссылок
11014        observeBlocks();
11015        trackAnchorClicks();
11016    };
11017});
11018
11019
11020document.addEventListener("lpc_init_after", function () { // вместо  DOMContentLoaded используем lpc_init_after чтобы работало в новом конструкторе, так как там нет события DOMContentLoaded
11021    let lpContent = document.getElementById("lp_constructor");
11022    let timeout = 20;
11023    if (lpContent) {
11024        timeout = 1500;
11025    }
11026    
11027    setTimeout(function () {
11028    	
11029	    const toRGBAArray = (rgbStr) => {
11030	        const values = rgbStr.match(/[\d.]+/g).map(Number);
11031	        
11032	        if (values.length === 3) values.push(1);
11033	        return values;
11034	    };
11035	
11036	    const baseTextColor = getComputedStyle(document.documentElement).getPropertyValue('--text-color-base-header').trim();
11037	
11038	    document.querySelectorAll('.has_custom_bg').forEach(function (element) {
11039	        const computedStyle = window.getComputedStyle(element);
11040	        const bgColor = computedStyle.backgroundColor;
11041	        const rgba = toRGBAArray(bgColor);
11042	        const alpha = rgba[3];
11043	       
11044	        if (bgColor === "transparent" || alpha === 0) {
11045	            element.style.color = baseTextColor;
11046	            element.querySelectorAll('[data-elem-type="text"], [data-elem-type="header"], [data-elem-type="generate"], .has-custom-bg-item').forEach(function (innerElem) {
11047	                innerElem.style.color = baseTextColor;
11048	            });
11049	            return;
11050	        }
11051	
11052	        const brightness = Math.round((rgba[0] * 299 + rgba[1] * 587 + rgba[2] * 114) / 1000);
11053	        const textColor = brightness > 150 ? baseTextColor : '#fff';
11054	
11055	        element.style.color = textColor;
11056	        element.querySelectorAll('[data-elem-type="text"], [data-elem-type="header"], [data-elem-type="generate"], .has-custom-bg-item').forEach(function (innerElem) {
11057	            innerElem.style.color = textColor;
11058	        });
11059	    });
11060	
11061	    document.querySelectorAll('.ya-share2').forEach(function (element) {
11062	        const computedStyle = window.getComputedStyle(element);
11063	        const rgba = toRGBAArray(computedStyle.backgroundColor);
11064	        const alpha = rgba[3];
11065	
11066	        const brightness = Math.round((rgba[0] * 299 + rgba[1] * 587 + rgba[2] * 114) / 1000);
11067	
11068	        if (alpha === 0 || computedStyle.backgroundColor === "transparent" || brightness > 150) {
11069	            element.classList.add("lpc-share-light-mode");
11070	        } else {
11071	            element.classList.add("lpc-share-dark-mode");
11072	        }
11073	    });
11074	}, timeout);
11075    
11076    
11077    /*setTimeout(function () {
11078
11079        const toRGBArray = rgbStr => rgbStr.match(/\d+/g).map(Number);
11080
11081        document.querySelectorAll('.has_custom_bg').forEach(function (element) {
11082            let customBg = toRGBArray(window.getComputedStyle(element).backgroundColor);
11083            let textColor = Math.round((parseInt(customBg[0]) * 299 + parseInt(customBg[1]) * 587 + parseInt(customBg[2]) * 114) / 1000);
11084
11085            if (textColor > 150) {
11086                element.style.color = '#000';
11087                element.querySelectorAll('[data-elem-type="text"]').forEach(function (textElement) {
11088                    textElement.style.color = '#000';
11089                });
11090                element.querySelectorAll('[data-elem-type="header"]').forEach(function (headerElement) {
11091                    headerElement.style.color = '#000';
11092                });
11093                element.querySelectorAll('[data-elem-type="generate"]').forEach(function (generateElement) {
11094                    generateElement.style.color = '#000';
11095                });
11096            } else {
11097                element.style.color = '#fff';
11098                element.querySelectorAll('[data-elem-type="text"]').forEach(function (textElement) {
11099                    textElement.style.color = '#fff';
11100                });
11101                element.querySelectorAll('[data-elem-type="header"]').forEach(function (headerElement) {
11102                    headerElement.style.color = '#fff';
11103                });
11104                element.querySelectorAll('[data-elem-type="generate"]').forEach(function (generateElement) {
11105                    generateElement.style.color = '#fff';
11106                });
11107            }
11108        });
11109        
11110        document.querySelectorAll('.ya-share2').forEach(function (element) {
11111            let customBgShare = toRGBArray(window.getComputedStyle(element).backgroundColor);
11112            let textColorShare = Math.round((parseInt(customBgShare[0]) * 299 + parseInt(customBgShare[1]) * 587 + parseInt(customBgShare[2]) * 114) / 1000);
11113
11114            if (textColorShare > 150) {
11115                $('.ya-share2').addClass("lpc-share-light-mode");
11116            } else {
11117                $('.ya-share2').addClass("lpc-share-dark-mode");
11118            }
11119        });
11120    }, timeout);*/
11121
11122    setTimeout(() => {
11123        const calculators = document.querySelectorAll('.lpc-calculator');
11124
11125        if (calculators.length) {
11126            calculators.forEach(calculator => {
11127                const calc = new Calculator(calculator);
11128                calc.init();
11129            });
11130        }
11131    }, 500);
11132});
11133
11134/*class Calculator {
11135	constructor(calculator) {
11136		this.calculator = calculator;
11137		this.calculateButton = this.calculator.querySelector('.calculate_button');
11138		this.calculateFormula = this.calculateButton.getAttribute('data-calculator-formula');
11139		this.calculateResult = this.calculator.querySelector('.js_calculate_result');
11140		this.calculateInputs = Array.from(this.calculator.querySelectorAll('input'));
11141		this.calculateErrorBlock = this.calculator.querySelector('.calculate-error-block');
11142	}
11143
11144	parseCalculatorFormula(formula) {
11145		let variableRegex = '([a-zA-Z0-9]?[a-zA-Z]+)';
11146		let formulaVariables = Array.from(formula.matchAll(variableRegex));
11147		let parsedFormula = formula;
11148		for (const formulaVariable of formulaVariables) {
11149			let inputValue = this.calculator.querySelector(`input[data-calculator-alias=${formulaVariable[0]}]`).value;
11150			parsedFormula = parsedFormula.replace(formulaVariable[0], inputValue ? inputValue : NULL);
11151		}
11152
11153		return eval(parsedFormula);
11154	}
11155
11156	initializeRangeFields(fields) {
11157		fields.forEach((field) => {
11158			let input = field;
11159			let parent = input.parentNode;
11160			let min = parseFloat(input.min);
11161			let max = parseFloat(input.max);
11162			let current = parent.querySelector(".lpc-calculator-range--current");
11163			let currentLine = parent.querySelector(".lpc-calculator-range--current-line");
11164
11165			const updateCurrentPosition = () => {
11166				let value = parseFloat(input.value);
11167				current.textContent = value;
11168
11169				let currentWidth = current.getBoundingClientRect().width;
11170				let currentPos = (100 * (value - min) / (max - min));
11171
11172				if (currentPos < 0) {
11173					currentPos = 0;
11174				} else if (currentPos > 100) {
11175					currentPos = 100;
11176				}
11177
11178				current.style.left = `${(currentPos / 100) * (input.getBoundingClientRect().width - currentWidth)}px`;
11179				currentLine.style.width = `${currentPos}%`;
11180			};
11181
11182			field.addEventListener("input", updateCurrentPosition);
11183			updateCurrentPosition();
11184		});
11185	}
11186
11187	initializeNumberFields(fields) {
11188		fields.forEach((field) => {
11189			let input = field;
11190			let parent = input.parentNode;
11191			let min = input.min;
11192			let step = input.step;
11193			let max = input.max;
11194			let decrementButton = parent.querySelector(".lpc-calculator-number--dec");
11195			let incrementButton = parent.querySelector(".lpc-calculator-number--inc");
11196	
11197			input.addEventListener("change", () => {
11198				const value = Number(input.value);
11199				if (value >= max) {
11200					incrementButton.setAttribute("disabled", true);
11201					decrementButton.removeAttribute("disabled");
11202					input.value = max;
11203				} else if (value <= min) {
11204					input.value = min;
11205					incrementButton.removeAttribute("disabled");
11206					decrementButton.setAttribute("disabled", true);
11207				} else {
11208					incrementButton.removeAttribute("disabled");
11209					decrementButton.removeAttribute("disabled");
11210				}
11211			});
11212	
11213			decrementButton.addEventListener("click", () => {
11214				incrementButton.disabled = false
11215				let current = input.value
11216				let currentVal = current - step
11217	
11218				if (currentVal <= min) {
11219					input.textContent = min
11220					decrementButton.disabled = true
11221					return input.value = min
11222				}
11223	
11224				input.textContent = currentVal
11225				return input.value = currentVal
11226			});
11227	
11228			incrementButton.addEventListener("click", () => {
11229				decrementButton.disabled = false
11230				let current = input.value
11231				let currentVal = Number(current) + Number(step)
11232	
11233				if (Number(currentVal) >= Number(max)) {
11234					incrementButton.disabled = true
11235					input.textContent = max
11236					return input.value = max
11237				}
11238	
11239				input.textContent = currentVal
11240				return input.value = currentVal
11241			});
11242		})
11243	}
11244
11245
11246	initializeFieldTypes() {
11247		let rangeFields = this.calculateInputs.filter((item) => item.classList.contains('lpc-calculator-input--range'));
11248		let numberFields = this.calculateInputs.filter((item) => item.classList.contains('lpc-calculator-input--number'));
11249
11250		this.initializeRangeFields(rangeFields);
11251		this.initializeNumberFields(numberFields);
11252	}
11253	
11254	init() {
11255	    this.initializeFieldTypes();
11256	    this.calculateButton.addEventListener('click', () => {
11257	        this.calculateErrorBlock.innerHTML = '';
11258	        try {
11259	            const result = this.parseCalculatorFormula(this.calculateFormula);
11260	            if (!isNaN(result) && isFinite(result)) {
11261	                this.calculateResult.querySelector('span').textContent = result.toFixed(2);
11262	                console.log(result);
11263	            } else {
11264	                this.calculateErrorBlock.innerHTML += '<p>Проверьте корректность введенных данных</p>';
11265	                this.calculateResult.querySelector('span').textContent = 0;
11266	            }
11267	        } catch (e) {
11268	            this.calculateErrorBlock.innerHTML += '<p>Проверьте корректность введенных данных</p>';
11269	            this.calculateResult.querySelector('span').textContent = 0;
11270	        }
11271	    });
11272	}
11273}*/
11274
11275class Calculator {
11276    constructor(calculator) {
11277        this.calculator = calculator;
11278        this.calculateButton = this.calculator.querySelector('.calculate_button');
11279        this.calculateFormula = this.calculateButton.getAttribute('data-calculator-formula');
11280        this.calculateResult = this.calculator.querySelector('.js_calculate_result');
11281        this.calculateInputs = Array.from(this.calculator.querySelectorAll('input'));
11282        this.calculateErrorBlock = this.calculator.querySelector('.calculate-error-block');
11283    }
11284 
11285    parseCalculatorFormula(formula) {
11286        let parsedFormula = formula;
11287        const values = {};
11288 
11289        /* 1. INPUT чекбоксы и текстовые поля */
11290        this.calculator
11291            .querySelectorAll('input.lpc-calculator-checkbox-formula')
11292            .forEach(input => {
11293                const name = input.name;
11294                if (!name) return;
11295 
11296                if (!values[name]) {
11297                    values[name] = 0;
11298                }
11299 
11300                if (
11301                    input.checked ||
11302                    (input.type === 'text' && input.value !== '')
11303                ) {
11304                    values[name] += Number(input.value) || 0;
11305                }
11306            });
11307 
11308        /* 2. DIV чекбоксы */
11309        this.calculator
11310            .querySelectorAll('.lpc-chechbox-block__input-only.active')
11311            .forEach(div => {
11312                const name = div.dataset.chechboxName;
11313                const value = div.dataset.chechboxValue;
11314 
11315                if (!name) return;
11316 
11317                if (!values[name]) {
11318                    values[name] = 0;
11319                }
11320 
11321                values[name] += Number(value) || 0;
11322            });
11323 
11324        /* 3. Подстановка значений в формулу */
11325        for (const name in values) {
11326            parsedFormula = parsedFormula.replaceAll(name, values[name]);
11327        }
11328 
11329        /* 4. Оставшиеся alias input */
11330        const variableRegex = /\b[a-zA-Z_][a-zA-Z0-9_]*\b/g;
11331        const variables = parsedFormula.match(variableRegex) || [];
11332 
11333        variables.forEach(variable => {
11334            const input = this.calculator.querySelector(
11335                `input[data-calculator-alias="${variable}"]`
11336            );
11337 
11338            if (input) {
11339                parsedFormula = parsedFormula.replaceAll(
11340                    variable,
11341                    Number(input.value) || 0
11342                );
11343            }
11344        });
11345 
11346        return eval(parsedFormula);
11347    }
11348    
11349    initializeRangeFields(fields) {
11350        fields.forEach((field) => {
11351            let input = field;
11352            let parent = input.parentNode;
11353            let min = parseFloat(input.min);
11354            let max = parseFloat(input.max);
11355            let current = parent.querySelector(".lpc-calculator-range--current");
11356            let currentLine = parent.querySelector(".lpc-calculator-range--current-line");
11357 
11358            const updateCurrentPosition = () => {
11359                let value = parseFloat(input.value);
11360                current.textContent = value;
11361 
11362                let currentWidth = current.getBoundingClientRect().width;
11363                let currentPos = (100 * (value - min) / (max - min));
11364 
11365                if (currentPos < 0) {
11366                    currentPos = 0;
11367                } else if (currentPos > 100) {
11368                    currentPos = 100;
11369                }
11370 
11371                current.style.left = `${(currentPos / 100) * (input.getBoundingClientRect().width - currentWidth)}px`;
11372                currentLine.style.width = `${currentPos}%`;
11373            };
11374 
11375            //field.addEventListener("input", updateCurrentPosition); //Старый вариант
11376            // 1. Событие 'change' — сработает, когда пользователь отпустил ползунок
11377			field.addEventListener("change", updateCurrentPosition);
11378			
11379			// 2. Дополнительно для мобильных устройств (touch-событие)
11380			field.addEventListener("touchend", updateCurrentPosition);
11381            updateCurrentPosition();
11382        });
11383    }
11384 
11385    initializeNumberFields(fields) {
11386        fields.forEach((field) => {
11387            let input = field;
11388            let parent = input.parentNode;
11389            let min = input.min;
11390            let step = input.step;
11391            let max = input.max;
11392            let decrementButton = parent.querySelector(".lpc-calculator-number--dec");
11393            let incrementButton = parent.querySelector(".lpc-calculator-number--inc");
11394    
11395            input.addEventListener("change", () => {
11396                const value = Number(input.value);
11397                if (value >= max) {
11398                    incrementButton.setAttribute("disabled", true);
11399                    decrementButton.removeAttribute("disabled");
11400                    input.value = max;
11401                } else if (value <= min) {
11402                    input.value = min;
11403                    incrementButton.removeAttribute("disabled");
11404                    decrementButton.setAttribute("disabled", true);
11405                } else {
11406                    incrementButton.removeAttribute("disabled");
11407                    decrementButton.removeAttribute("disabled");
11408                }
11409                if (input.classList.contains('lpc-calculator-checkbox-input-js')) {
11410				    var wrapper = input.closest('.lpc-chechbox-block__item'); 				    
11411				    if (wrapper) {
11412				        var inputItem = wrapper.querySelector('.lpc-chechbox-block__input');
11413				        if (inputItem) {
11414				            var inputValue = inputItem.dataset.valueCheckbox * input.value;
11415				            inputItem.value = inputValue;
11416				        }
11417				    }
11418				}
11419            });
11420    
11421            decrementButton.addEventListener("click", () => {
11422                incrementButton.disabled = false
11423                let current = input.value
11424                let currentVal = current - step
11425    
11426                if (currentVal <= min) {
11427                    input.textContent = min
11428                    decrementButton.disabled = true
11429                    return input.value = min
11430                }
11431    
11432                input.textContent = currentVal;
11433                input.value = currentVal;
11434                if (input.classList.contains('lpc-calculator-checkbox-input-js')) {
11435				    var wrapper = input.closest('.lpc-chechbox-block__item'); 				    
11436				    if (wrapper) {
11437				        var inputItem = wrapper.querySelector('.lpc-chechbox-block__input');
11438				        if (inputItem) {
11439				            var inputValue = inputItem.dataset.valueCheckbox * input.value;
11440				            inputItem.value = inputValue;
11441				        }
11442				    }
11443				}
11444                
11445                return 
11446                
11447            });
11448    
11449            incrementButton.addEventListener("click", () => {
11450                decrementButton.disabled = false
11451                let current = input.value
11452                let currentVal = Number(current) + Number(step)
11453    
11454                if (Number(currentVal) >= Number(max)) {
11455                    incrementButton.disabled = true
11456                    input.textContent = max
11457                    return input.value = max
11458                }
11459    
11460                input.textContent = currentVal;
11461                input.value = currentVal;
11462                if (input.classList.contains('lpc-calculator-checkbox-input-js')) {
11463				    var wrapper = input.closest('.lpc-chechbox-block__item'); 				    
11464				    if (wrapper) {
11465				        var inputItem = wrapper.querySelector('.lpc-chechbox-block__input');
11466				        if (inputItem) {
11467				            var inputValue = inputItem.dataset.valueCheckbox * input.value;
11468				            inputItem.value = inputValue;
11469				        }
11470				    }
11471				}
11472                return 
11473                
11474            });
11475        })
11476    }
11477 
11478    initializeSelectField() {
11479        this.calculator.addEventListener('click', (e) => {
11480            const target = e.target.closest('.js-calculator-select');
11481            if (!target || !this.calculator.contains(target)) return;
11482 
11483            const checkedClass = '_checked';
11484            const thisText = target.textContent;
11485            const parentSelect = target.closest('.lpс-calculator__field-select');
11486            const ariaLabel = target.getAttribute('aria-label');
11487 
11488            if (!parentSelect) return;
11489 
11490            if (!target.classList.contains(checkedClass)) {
11491                parentSelect.querySelectorAll('.js-calculator-select').forEach(el => {
11492                    el.classList.remove(checkedClass);
11493                });
11494 
11495                target.classList.add(checkedClass);
11496 
11497                const label = parentSelect.querySelector('.lpс-calculator__field-select__input');
11498                if (label) {
11499                    label.textContent = thisText;
11500                }
11501 
11502                const hiddenInput = parentSelect.parentElement.querySelector('input');
11503                if (hiddenInput) {
11504                    hiddenInput.value = ariaLabel;
11505                }
11506            }
11507            parentSelect.classList.remove('_opened');
11508        });
11509    }
11510 
11511    initializeCheckboxImages() {
11512        const blockList = this.calculator.querySelector('.lpc-chechbox-img-only');
11513        if (!blockList) return;
11514 
11515        const items = blockList.querySelectorAll('.lpc-chechbox-block__input-only');
11516 
11517        blockList.addEventListener('click', (e) => {
11518            e.stopPropagation();
11519            const item = e.target.closest('.lpc-chechbox-block__input-only');
11520 
11521            if (!item || !blockList.contains(item)) return;
11522 
11523            if( item.classList.contains('active') ){
11524                item.classList.remove('active');
11525            }else {
11526                items.forEach(el => el.classList.remove('active'));
11527                item.classList.add('active');
11528            }
11529        });
11530    }
11531 
11532    initializeFieldTypes() {
11533        let rangeFields = this.calculateInputs.filter((item) => item.classList.contains('lpc-calculator-input--range'));
11534        let numberFields = this.calculateInputs.filter((item) => item.classList.contains('lpc-calculator-input--number'));
11535 
11536        this.initializeRangeFields(rangeFields);
11537        this.initializeNumberFields(numberFields);
11538 
11539        this.initializeSelectField();
11540 
11541        this.initializeCheckboxImages();
11542    }
11543 
11544    
11545    init() {
11546        this.initializeFieldTypes();
11547        this.calculateButton.addEventListener('click', () => {
11548            this.calculateErrorBlock.innerHTML = '';
11549            try {
11550                const result = this.parseCalculatorFormula(this.calculateFormula);
11551                if (!isNaN(result) && isFinite(result)) {
11552                    this.calculateResult.querySelector('span').textContent = result.toFixed(2);
11553                    console.log(result);
11554                } else {
11555                    this.calculateErrorBlock.innerHTML += '<p>Проверьте корректность введенных данных</p>';
11556                    this.calculateResult.querySelector('span').textContent = 0;
11557                }
11558            } catch (e) {
11559                console.log(result);
11560                this.calculateErrorBlock.innerHTML += '<p>Проверьте корректность введенных данных</p>';
11561                this.calculateResult.querySelector('span').textContent = 0;
11562            }
11563        });
11564    }
11565}
11566
11567/*const lpcQueryString = window.location.search; // НЕ УДАЛЯТЬ - НГ оформление
11568
11569if (lpcQueryString.includes('lpc_disable_snow')) {
11570	
11571	createCookie('lpc_disable_snow', 1, 30);
11572}
11573
11574function letItSnow() { 
11575	  var COUNT = 30;
11576	  var masthead = document.querySelector('.sky');
11577	  var canvas = document.createElement('canvas');
11578	  var ctx = canvas.getContext('2d');
11579	  var width = masthead.clientWidth;
11580	  var height = masthead.clientHeight;
11581	  var i = 0;
11582	  var active = false;
11583	
11584	  function onResize() {
11585	    width = masthead.clientWidth;
11586	    height = masthead.clientHeight;
11587	    canvas.width = width;
11588	    canvas.height = height;
11589	    ctx.fillStyle = '#FFF';
11590	
11591	    var wasActive = active;
11592	    active = width > 600;
11593	
11594	    if (!wasActive && active)
11595	      requestAnimFrame(update);
11596	  }
11597	
11598	  var Snowflake = function () {
11599	    this.x = 0;
11600	    this.y = 0;
11601	    this.vy = 0;
11602	    this.vx = 0;
11603	    this.r = 0;
11604	
11605	    this.reset();
11606	  }
11607	
11608	  Snowflake.prototype.reset = function() {
11609	    this.x = Math.random() * width;
11610	    this.y = Math.random() * -height;
11611	    this.vy = 1 + Math.random() * 3;
11612	    this.vx = 0.5 - Math.random();
11613	    this.r = 1 + Math.random() * 2;
11614	    this.o = 0.5 + Math.random() * 0.5;
11615	  }
11616	
11617	  canvas.style.position = 'absolute';
11618	  canvas.style.left = canvas.style.top = '0';
11619	
11620	  var snowflakes = [], snowflake;
11621	  for (i = 0; i < COUNT; i++) {
11622	    snowflake = new Snowflake();
11623	    snowflake.reset();
11624	    snowflakes.push(snowflake);
11625	  }
11626	
11627	  function update() {
11628	
11629	    ctx.clearRect(0, 0, width, height);
11630	
11631	    if (!active)
11632	      return;
11633	
11634	    for (i = 0; i < COUNT; i++) {
11635	      snowflake = snowflakes[i];
11636	      snowflake.y += snowflake.vy;
11637	      snowflake.x += snowflake.vx;
11638	
11639	      ctx.globalAlpha = snowflake.o;
11640	      ctx.beginPath();
11641	      ctx.arc(snowflake.x, snowflake.y, snowflake.r, 0, Math.PI * 2, false);
11642	      ctx.closePath();
11643	      ctx.fill();
11644	
11645	      if (snowflake.y > height) {
11646	        snowflake.reset();
11647	      }
11648	    }
11649	
11650	    requestAnimFrame(update);
11651	  }
11652	
11653	  // shim layer with setTimeout fallback
11654	  window.requestAnimFrame = (function(){
11655	    return  window.requestAnimationFrame       ||
11656	            window.webkitRequestAnimationFrame ||
11657	            window.mozRequestAnimationFrame    ||
11658	            function( callback ){
11659	              window.setTimeout(callback, 1000 / 60);
11660	            };
11661	  })();
11662	
11663	  onResize();
11664	  window.addEventListener('resize', onResize, false);
11665	
11666	  masthead.appendChild(canvas);
11667};*/

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.