PageSourceSearch

https://www.mirkrasok.ru/local/templates/mirkrasok_2026v2/js/main.js?1789766230162997

js mirkrasok.ru collected 2026-10-03 20:58:17 UTC 162,997 bytes, 4,415 lines download raw bytes

1const RRC_FROM = 0;
2const MRC_FROM = 20000;
3const PRC_FROM = 30000;
4const BOC1_FROM = 70000;
5
6$(document).on("focus",'[name="tk_delivery_datebirth"]',()=>{
7    $('[name="tk_delivery_datebirth"]').mask('99.99.9999');
8})
9
10function sendYandexMetrikaGoal(goal) {
11    if (typeof window.ym != "undefined") {
12        ym(7500958, "reachGoal", goal);
13    }
14}
15
16$(document).on("click", 'a[href*="t.me"], a[href*="telegram.me"], a[href*="max.ru"]', function () {
17    sendYandexMetrikaGoal("click_messenger");
18});
19
20$(document).on("click", ".add-to-cart, .--gtm-btn_buy", function () {
21    sendYandexMetrikaGoal(".btn_buy");
22});
23
24$(document).on("click", '[onclick*="obCallback.show"]', function () {
25    sendYandexMetrikaGoal("open_zvonok");
26});
27
28$(document).on("click", 'a[onclick*="obFastRezerv.get"]', function () {
29    sendYandexMetrikaGoal("vrezerv_select");
30});
31
32var obChangeNumberAnimation = {
33    time: 100,
34    step: 10,
35
36    outNum: function (num, elem) {
37        let e = elem;
38        if (num > 1000) {
39            n = 10;
40            obChangeNumberAnimation.step = 30;
41        } else {
42            n = 1;
43            obChangeNumberAnimation.step = 30;
44        }
45        if (num > 10000) {
46            n = 100;
47            obChangeNumberAnimation.step = 100;
48        }
49
50        let t = Math.round(obChangeNumberAnimation.time / (num / obChangeNumberAnimation.step));
51        let interval = setInterval(() => {
52
53            n = n + obChangeNumberAnimation.step;
54            if (n > num) {
55                e.innerHTML = obChangeNumberAnimation.number_format(num, 0, ".", " ") + " ₽";
56                clearInterval(interval);
57            } else {
58                e.innerHTML = obChangeNumberAnimation.number_format(n, 0, ".", " ") + " ₽";
59
60            }
61
62
63        }, t);
64    },
65    number_format: function (number, decimals, dec_point, thousands_sep) {	// Format a number with grouped thousands
66        //
67        // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
68        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
69        // +	 bugfix by: Michael White (http://crestidg.com)
70
71        var i, j, kw, kd, km;
72
73        // input sanitation & defaults
74        if (isNaN(decimals = Math.abs(decimals))) {
75            decimals = 2;
76        }
77        if (dec_point == undefined) {
78            dec_point = ",";
79        }
80        if (thousands_sep == undefined) {
81            thousands_sep = ".";
82        }
83
84        i = parseInt(number = (+number || 0).toFixed(decimals)) + "";
85
86        if ((j = i.length) > 3) {
87            j = j % 3;
88        } else {
89            j = 0;
90        }
91
92        km = (j ? i.substr(0, j) + thousands_sep : "");
93        kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
94        //kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
95        kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");
96
97
98        return km + kw + kd;
99    }
100    ,
101
102
103    intiChangeNumberAnimation: function () {
104        $("td.price.total").each(function (element) {
105
106            obChangeNumberAnimation.outNum($(this).data("price-value"), this);
107        })
108
109    }
110
111}
112
113var obWishList = {
114    self: "",
115    parrent: "",
116    idProduct: "",
117    toogleActive: function (self, parrent) {
118        $(self).toggleClass("wish-list-button-active");
119        $(parrent).toggleClass("wish-list-box-active");
120        $(parrent).parent(".wish-list").toggleClass("wish-list-active");
121
122    },
123    click: function (self) {
124
125        this.self = self;
126        this.parrent = $(this.self).parent();
127        this.idProduct = $(this.self).data("product-id");
128        this.ajax(this.idProduct);
129
130    },
131    ajax: function (idProduct) {
132        $this = this;
133        $.ajax({
134            type: "POST",
135            url: "/local/php_interface/ajax/ajax.wishList.php",
136            data: {"PRODUCT_ID": $this.idProduct},
137
138            beforeSend: function () {
139            },
140            success: function (data) {
141                console.log($this);
142                $this.toogleActive($this.self, $this.parrent);
143            },
144            error: function () {
145
146            }
147        });
148    }
149
150}
151
152var obMain = {
153
154    headerHeight: 0,
155
156    bindScroll: function () {
157        var $header = $("header");
158        obMain.headerHeight = $header.height();
159        $(window).on("scroll", function () {
160            var fromTop = $(window).scrollTop();
161            var $container = $("[data-container]");
162            $container.toggleClass("fixed", (fromTop > obMain.headerHeight));
163        });
164    },
165
166    init: (function () {
167
168        $(function () {
169            obMain.bindScroll();
170        });
171
172
173    })()
174};
175
176var obBrowser = {
177    init: (function () {
178        $(function () {
179            if ($.browser.opera) {
180                $("body").addClass("browser-opera");
181            }
182        });
183    })()
184};
185
186var obProduct = {
187    changeStateDelive: function (self, iQuantity) {
188        let $obProduct = $(self).parents("[data-parent]:first");
189        if($($obProduct).find(".btn_buy").data("gtm")){
190            let price = $($obProduct).find(".btn_buy").data("gtm").price;
191            let delivery_remain = $('[data-delivery-remain]').data("delivery-remain");
192            console.log(delivery_remain > price * iQuantity);
193            if (delivery_remain > price * iQuantity) {
194                $("[delivery-cost]").html("550")
195            } else {
196                $("[delivery-cost]").html("0")
197            }
198        }
199
200    },
201    changeQuant: function (self, sTurn) {
202        // Находим родительский контейнер
203        var $container = $(self).closest('.product-cart-control');
204
205        // Извлекаем data-sku-id
206        var skuId = $container.data('sku-id');
207        var sku = window.location.pathname.match(/sku_(\d+)/)?.[1];
208
209        // Определяем текущее количество
210        var $quantityInput = $container.find('input[data-quantity="true"]');
211        var currentQuantity = parseInt($quantityInput.val());
212
213        // Вычисляем новое количество в зависимости от действия
214        var newQuantity = currentQuantity;
215        if (sTurn === 'minus') {
216            newQuantity = currentQuantity - 1;
217            if (newQuantity < 0) newQuantity = 0; // Минимальное значение 1
218        } else if (sTurn === 'plus') {
219            newQuantity = currentQuantity + 1;
220        } else {
221            // Если вызвано через onchange, берем значение из поля
222            newQuantity = parseInt(self.value);
223            if (isNaN(newQuantity)) newQuantity = 1;
224        }
225        if(skuId=='' && sku){
226            skuId = sku;
227        }
228        // Отправляем AJAX запрос
229        $.ajax({
230            type: "POST",
231            url: "/local/components/art-fresh/sale.basket/ajax_new.php",
232            data: {
233                action: "change",
234                SKU_ID: skuId,
235                QUANTITY: newQuantity
236            },
237            timeout: 15000,
238            beforeSend: function () {
239                // Можно добавить индикатор загрузки
240                $container.addClass("loading");
241            },
242            success: function (data, textstatus) {
243                console.log("Success:", data);
244                $('.icon-link.cart-link span').html(data);
245                $('.link-cart span').html(data);
246
247
248                var price = $('#curprice').val();
249                var oldprice = $('#curoldprice').val();
250                var cursku = $('#cursku').val();
251                var curbonus = $('#curbonus').val();
252
253                if(newQuantity==0){newQuantity=1;}
254                if(price>0 && skuId==cursku){
255                    var $basePrice = $('.right-sidebar-price-row.--price-box .right-sidebar-price-title.--price-value');
256                    var $tintRow = $('.right-sidebar-price-row.new-price').first();
257                    var tintUnitPrice = parseFloat($tintRow.attr('data-unit-price'));
258                    var baseTotal = price * newQuantity;
259
260                    $basePrice.text(BX.Currency.currencyFormat(baseTotal, 'RUB', true));
261
262                    if ($tintRow.length && isFinite(tintUnitPrice)) {
263                        var tintTotal = tintUnitPrice * newQuantity;
264                        var tintTotalFormatted = BX.Currency.currencyFormat(tintTotal, 'RUB', true);
265                        $tintRow.find('.right-sidebar-price-title.--price-value').text(tintTotalFormatted);
266                        $('.mk-cartbar-price').text(tintTotalFormatted);
267                    } else {
268                        $('.mk-cartbar-price').text(BX.Currency.currencyFormat(baseTotal, 'RUB', true));
269                    }
270                    $('.sum-discount .sum').text(BX.Currency.currencyFormat((price-oldprice)*newQuantity, 'RUB', true));
271                    $('.--bonus-value').text('+ ' + BX.Currency.currencyFormat(curbonus*newQuantity, 'RUB', true));
272                }
273            },
274            error: function (xhr, status, error) {
275                console.error("Ошибка AJAX:", error);
276                // Возвращаем старое значение при ошибке
277                $quantityInput.val(currentQuantity);
278            },
279            complete: function () {
280                $container.removeClass("loading");
281            }
282        });
283
284        return false;
285    },
286    changeQuantity: function (self, sTurn, bRefresh) {
287        'use strict';
288        var $obParent = $(self).parents("[data-quantity-parent]:first");
289        var $obQuantity = $obParent.find("[data-quantity]");
290        var iQuantity = IntVal($obQuantity.val());
291        var $obProduct = $(self).parents("[data-parent]:first");
292        var obParentData = $obProduct.data();
293        var iProductID = obParentData.productId;
294        var iMinValue = ($obQuantity.hasAttr("data-min-value")) ? IntVal($obQuantity.attr("data-min-value")) : 1;
295        console.log(obParentData)
296        if (!!sTurn) {
297            switch (sTurn) {
298                case "plus":
299                    iQuantity++;
300                    break;
301                case "minus":
302                    if (iQuantity > iMinValue) iQuantity--;
303                    break;
304            }
305        } else {
306            iQuantity = IntVal(iQuantity);
307        }
308        if (iQuantity < 0) return; //iQuantity=1;
309        obProduct.productAdded(iProductID, false);
310        $obQuantity.val(iQuantity).attr("data-changed", 1);
311
312        console.log('$obQuantity', $obQuantity)
313        if (!!bRefresh) {
314            $obQuantity.stopTime();
315            $obQuantity.oneTime("300ms", function () {
316                obBasket.refreshBasket($obQuantity[0]);
317            });
318        }
319        this.changeStateDelive(self, iQuantity);
320        return false;
321    },
322
323    changeQuantityRez: function (self, sTurn, bRefresh) {
324        'use strict';
325        var $obParent = $(self).parents("[data-quantity-parent]:first");
326        var $obQuantity = $obParent.find("[data-quantity-rezerv]");
327        var iQuantity = IntVal($obQuantity.val());
328        var $obProduct = $(self).parents("[data-parent]:first");
329        var obParentData = $obProduct.data();
330        var iProductID = obParentData.productId;
331        var iMinValue = ($obQuantity.hasAttr("data-min-value")) ? IntVal($obQuantity.attr("data-min-value")) : 1;
332        if (!!sTurn) {
333            switch (sTurn) {
334                case "plus":
335                    iQuantity++;
336                    break;
337                case "minus":
338                    if (iQuantity > iMinValue) iQuantity--;
339                    break;
340            }
341        } else {
342            iQuantity = IntVal(iQuantity);
343        }
344        if (iQuantity < 0) return; //iQuantity=1;
345        obProduct.productAdded(iProductID, false);
346        $obQuantity.val(iQuantity).attr("data-changed", 1);
347        if (!!bRefresh) {
348            $obQuantity.stopTime();
349            $obQuantity.oneTime("300ms", function () {
350                obBasket.refreshBasket($obQuantity[0]);
351            });
352        }
353        return false;
354    },
355
356    deleteFromBasket: function (self) {
357        'use strict';
358
359        ym(7500958, 'reachGoal', 'product-remove-from-cart');
360        var gtm = $(self).data("gtm");
361        var $obParent = $(self).parents("[data-parent]:first");
362        var $obForm = $obParent.parents("form:first");
363        var obData = $obParent.data();
364        var iProductID = obData.productId;
365        var $obGroup = $obParent.parents("[data-element]:first");
366        $obParent.remove();
367        if (!$obGroup.find("[data-basket-item]").length) $obGroup.remove();
368        if (IntVal(iProductID)) {
369            obProduct.productAdded(iProductID, false);
370        }
371
372
373        if ($obForm.length) {
374            obBasket.refreshBasket($obForm[0]);
375        }
376
377        if (typeof gtm != "undefined") {
378            dataLayer.push({
379                "ecommerce": {
380                    'currencyCode': 'RUB',
381                    "remove": { // для добавления товара из корзины
382                        "products": [gtm]
383                    }
384                },
385                'event': 'pixel-mg-event',	// Обязательно
386                'pixel-mg-event-category': 'Enhanced Ecommerce',	// Обязательно
387                'pixel-mg-event-action': 'Removing a Product from a Shopping Cart',	// Обязательно
388                'pixel-mg-event-non-interaction': 'False'	// Обязательно
389
390            });
391            console.log(gtm);
392        }
393
394    },
395
396    deleteGroup: function (self) {
397        'use strict';
398
399        var $obParent = $(self).parents("[data-element]:first");
400        var $obForm = $obParent.parents("form:first");
401        var $items = $obParent.find("[data-gtm]");
402        $obParent.remove();
403        if ($obForm.length) obBasket.refreshBasket($obForm[0]);
404        if ($items.length) {
405            var products = [];
406            $items.each(function () {
407                var gtm = $(this).data("gtm");
408
409                if (typeof gtm != "undefined") {
410                    products.push(gtm);
411                }
412            });
413            dataLayer.push({
414                "ecommerce": {
415                    "remove": { // для добавления товара из корзины
416                        "products": products
417                    }
418                }
419            });
420        }
421    },
422
423    productAdded: function (iProductID, bTurn) {
424
425        var $obAddBlocks = $("[data-product-id=" + iProductID + "] [data-add-block=add]");
426        var $obAddedBlocks = $("[data-product-id=" + iProductID + "] [data-add-block=added]");
427        if (!bTurn) {
428
429            $obAddBlocks.removeClass("hidden");
430            $obAddedBlocks.addClass("hidden");
431        } else {
432            $obAddBlocks.addClass("hidden");
433            $obAddedBlocks.removeClass("hidden");
434        }
435
436        return false;
437
438    },
439    productShowPopup: function (iProductID, bTurn, quantity, price) {
440        if (notificationProduct !== undefined) {
441            notificationProduct.show();
442        }
443        /* $.fancybox({
444             href: `/local/components/art-fresh/catalog.popup_add_to_basket/ajax.php?SKU_ID=${iProductID}&QUANTITY=${quantity}&CURRENT_PRICE=${price}` ,
445             type: 'ajax',
446             maxWidth: '1024px',
447             css: {}
448         });*/
449        return false;
450
451    },
452    productClosePopup: function (event) {
453
454        $.fancybox.close();
455
456        return false;
457
458    },
459
460addToBasket: function (self) {
461    'use strict';
462
463    var $obLink = $(self);
464    var gtm = $obLink.data("gtm");
465    var $obParent = $(self).parents("[data-parent]:first");
466    var is_old_price = $obLink.data("is-old-price");
467    var $obQuantity = $obParent.find("[data-quantity]");
468    var obParentData = $obParent.data();
469    var iQuantity = 1;
470
471    var iProductID = obParentData.productId;
472
473    if ($obQuantity.length && IntVal($obQuantity.val())) {
474        iQuantity = IntVal($obQuantity.val());
475    }
476
477    var $obFly = $("[data-to-fly]");
478    var $obImage = $(["data-fly"]);
479
480    if (iProductID && iQuantity) {
481
482        var obData = {action: "add", "ELEMENT_ID": iProductID, "QUANTITY": iQuantity};
483        var iColorID = false;
484        if (iColorID = IntVal($obParent.data("color-id"))) {
485            obData.COLOR_ID = iColorID;
486        }
487        var iColorVolume = 1;
488        if (iColorVolume = IntVal($obParent.data("volume"))) {
489            obData.VOLUME = iColorVolume;
490        }
491        if (!$obLink.hasClass("loading")) {
492            var bBigBasket = $("[data-big-basket]").length ? 1 : 0;
493            var dFixedBasket = $("[data-fixed-basket]").length ? 1 : 0;
494            var dPopupBasket = $("[data-popup-basket]").length ? 1 : 0;
495            var dComparsion = $("[data-comparsion-parent]").length ? 1 : 0;
496            if (is_old_price) {
497                obData.IS_OLD_PRICE = 1;
498            }
499            if (dFixedBasket) {
500                obData.FIXED_BASKET = 1;
501            }
502            if (dPopupBasket) {
503                obData.POPUP_BASKET = 1;
504            }
505            if (bBigBasket) {
506                obData.BIG_BASKET = 1;
507            } else if ($("[data-big-basket-new]").length) {
508                obData.BIG_BASKET = 1;
509                obData.COLORATE_USE = "Y";
510                obData.basket_new = "Y";
511            }
512            if (dComparsion) {
513                obData.COMPARSION = 1;
514            }
515            var vendor = $obLink.data("vendor");
516            if (vendor && vendor.length) {
517                obData.vendor = vendor;
518            }
519
520            // Определяем, находимся ли мы на странице корзины
521            var isCartPage = window.location.pathname.includes('/personal/cart/');
522
523            console.log('добавлено в корзину');
524
525            // Выбираем URL в зависимости от страницы
526            var ajaxUrl = isCartPage 
527                ? "/local/components/art-fresh/sale.basket/ajax.php" 
528                : "/local/components/art-fresh/sale.basket/ajax_new.php";
529
530            $.ajax({
531                type: "POST",
532                url: ajaxUrl,
533                data: obData,
534                timeout: 15000,
535                beforeSend: function () {
536                    if ($obFly.length && $obImage.length) {
537                        //$obImage.fly($obFly);
538                    }
539                    $obParent.addClass("loading");
540                },
541                success: function (data, textstatus) {
542                    $obParent.removeClass("loading");
543
544                    if (isCartPage) {
545                        // На странице корзины - data содержит полный HTML корзины
546                        
547                        // Извлекаем количество товаров из HTML
548                        var count = 0;
549                        var $dataHtml = $(data);
550                        // Ищем элемент с количеством (data-count или из формы)
551                        var $countElement = $dataHtml.find('[data-count]');
552                        if ($countElement.length) {
553                            count = parseInt($countElement.attr('data-count')) || 0;
554                        } else {
555                            // Альтернативный способ - ищем текст "товара" или число в заголовке
556                            var $header = $dataHtml.find('h1');
557                            if ($header.length) {
558                                var match = $header.text().match(/(\d+)\s*товар/);
559                                if (match) {
560                                    count = parseInt(match[1]) || 0;
561                                }
562                            }
563                        }
564                        
565                        // Если не нашли, ищем в другом месте
566                        if (!count) {
567                            var $totalItems = $dataHtml.find('[data-total-summary]').closest('.basketn__total__item').find('.first');
568                            if ($totalItems.length) {
569                                var match = $totalItems.text().match(/(\d+)\s*товар/);
570                                if (match) {
571                                    count = parseInt(match[1]) || 0;
572                                }
573                            }
574                        }
575
576                        // Обновляем счетчики
577                        if (count) {
578                            $('.icon-link.cart-link span').html(count);
579                            $('.link-cart span').html(count);
580                        }
581
582                        // Обновляем корзину
583                        if (typeof obBasket !== 'undefined') {
584                            obBasket.changeBasket(data);
585                        }
586                        if (typeof obBigBasket !== 'undefined') {
587                            obBigBasket.changeBasket(data);
588                        }
589                    } else {
590                        // На остальных страницах обновляем только счетчики
591                        $('.icon-link.cart-link span').html(data);
592                        $('.link-cart span').html(data);
593                    }
594
595                    // Обработка попапа
596                    if ($(self).hasClass('showPopup')) {
597                        // На странице корзины data - это HTML, ищем цену
598                        var price = null;
599                        if (isCartPage) {
600                            var $dataHtml = $(data);
601                            var $productItem = $dataHtml.find(`[data-product-id=${iProductID}]`);
602                            if ($productItem.length) {
603                                price = $productItem.find('[data-price]').text().trim();
604                                price = parseInt(price.replace(/[^\d]/g, ''));
605                            }
606                        } else {
607                            price = $(data).find(`[data-product-id=${iProductID}]`).data('price');
608                        }
609                        obProduct.productShowPopup(iProductID, false, iQuantity, price);
610                    }
611
612                    // GTM
613                    if (typeof gtm != "undefined") {
614                        gtm.quantity = iQuantity;
615                        dataLayer.push({
616                            "ecommerce": {
617                                'currencyCode': 'RUB',
618                                "add": {
619                                    "products": [gtm]
620                                }
621                            },
622                            'goods_id': gtm.id,
623                            'goods_price': gtm.price,
624                            'page_type': 'add_product',
625                            'event': 'pixel-mg-event',
626                            'pixel-mg-event-category': 'Enhanced Ecommerce',
627                            'pixel-mg-event-action': 'Adding a Product to a Shopping Cart',
628                            'pixel-mg-event-non-interference': 'False'
629                        });
630                    }
631                },
632                error: function () {
633                    $obParent.removeClass("loading");
634                }
635            });
636        }
637    }
638    return false;
639},
640addColor(PRODUCT_ID, COLOR_ID, BARCODE){
641    setTimeout(()=>{
642        $.ajax({
643            url: "/local/ajax/addcolor.php",
644            method: "POST",
645            data: {
646                "PRODUCT_ID": PRODUCT_ID,
647                "COLOR_ID": COLOR_ID,
648                "BARCODE": BARCODE,
649            },
650            success: function(data) {
651                console.log("Цвет добавлен:", data);
652                $.ajax({
653                    url: "/local/components/art-fresh/sale.basket/ajax.php",
654                    method: "POST",
655                    data: data,
656                    success: function(response) {
657                        console.log(response);
658                    },
659                    error: function(xhr, status, error) {
660                        console.error("Ошибка второго запроса:", error);
661                    }
662                });
663            },
664            error: function(xhr, status, error) {
665                console.error("Ошибка первого запроса:", error);
666            }
667        });
668    }, 1000);
669},
670    addToBasketDirect: function (productId, quant, button) {
671        'use strict';
672
673        var $obLink = $(button);
674        //     var $obParent = $(self).parents("[data-parent]:first");
675
676        //      var $obQuantity = $obParent.find("[data-quantity]");
677        //      var obParentData = $obParent.data();
678
679        var iQuantity = quant;
680        var iProductID = productId;
681        // if ($obQuantity.length) {
682        //    iQuantity = IntVal($obQuantity.val());
683        //}
684
685        var $obFly = $("[data-to-fly]");
686        var $obImage = $(["data-fly"]);
687
688
689        if (iProductID && iQuantity) {
690
691            var obData = {action: "add", "ELEMENT_ID": iProductID, "QUANTITY": iQuantity};
692            var iColorID = false;
693            //    if (iColorID = IntVal($obParent.data("color-id"))) {
694            //       obData.COLOR_ID = iColorID;
695            //  }
696
697            if (!$obLink.hasClass("loading")) {
698                var bBigBasket = $("[data-big-basket]").length ? 1 : 0;
699                var dFixedBasket = $("[data-fixed-basket]").length ? 1 : 0;
700                var dPopupBasket = $("[data-popup-basket]").length ? 1 : 0;
701
702                if (dFixedBasket) {
703                    obData.FIXED_BASKET = 1;
704                }
705                if (dPopupBasket) {
706                    obData.POPUP_BASKET = 1;
707                }
708                if (bBigBasket) {
709                    obData.BIG_BASKET = 1;
710                }
711
712                $.ajax({
713                    type: "POST",
714                    url: "/local/components/art-fresh/sale.basket/ajax_new.php",
715                    data: obData,
716                    timeout: 15000,
717                    beforeSend: function () {
718                        if ($obFly.length && $obImage.length) {
719                            //$obImage.fly($obFly);
720                        }
721                        //     $obParent.addClass("loading");
722                    },
723                    success: function (data, textstatus) {
724                        //          $obParent.removeClass("loading");
725
726                $('.icon-link.cart-link span').html(data);
727                $('.link-cart span').html(data);
728                        obProduct.productAdded(iProductID, true);
729                       // obBasket.changeBasket(data);
730                    },
731                    error: function () {
732                        //          $obParent.removeClass("loading");
733                    }
734                });
735            }
736        }
737        return false;
738    },
739
740
741    addToBasketActionSku: function (productId, button) {
742        'use strict';
743
744        var $obLink = $(button);
745
746        var iQuantity = 1;
747        var iProductID = productId;
748
749        var $obFly = $("[data-to-fly]");
750        var $obImage = $(["data-fly"]);
751
752
753        if (iProductID && iQuantity) {
754
755            var obData = {action: "add", "ELEMENT_ID": iProductID, "QUANTITY": iQuantity};
756            var iColorID = false;
757
758            if (!$obLink.hasClass("loading")) {
759                var bBigBasket = $("[data-big-basket]").length ? 1 : 0;
760                var dFixedBasket = $("[data-fixed-basket]").length ? 1 : 0;
761                var dPopupBasket = $("[data-popup-basket]").length ? 1 : 0;
762
763                if (dFixedBasket) {
764                    obData.FIXED_BASKET = 1;
765                }
766                if (dPopupBasket) {
767                    obData.POPUP_BASKET = 1;
768                }
769                if (bBigBasket) {
770                    obData.BIG_BASKET = 1;
771                }
772
773                $.ajax({
774                    type: "POST",
775                    url: "/local/components/art-fresh/sale.basket/ajax_new.php",
776                    data: obData,
777                    timeout: 15000,
778                    beforeSend: function () {
779                        $obLink.addClass("loading");
780                    },
781                    success: function (data, textstatus) {
782                        $obLink.removeClass("loading");
783
784                        obProduct.productAdded(iProductID, true);
785                        //obBasket.changeBasket(data);
786
787                $('.icon-link.cart-link span').html(data);
788                $('.link-cart span').html(data);
789
790                        $obLink.attr('onclick', '');
791                        $obLink.attr('href', '/personal/cart/');
792                        $obLink.html('Оформить<span class="add_baket"></span>');
793                    },
794                    error: function () {
795                        $obLink.removeClass("loading");
796                    }
797                });
798            }
799        }
800        return false;
801    },
802
803    quantityHover: function () {
804        $("[data-item] [data-quantity-icon]").hover(function () {
805            var $popup = $(this).find("[data-drop]");
806            if ($popup.outerWidth() + $popup.offset().left > $(window).width()) {
807                $popup.addClass("right");
808            } else $popup.removeClass("right");
809        });
810
811    },
812
813    verticalAlign: function (iMax) {
814        //$("[data-product-item]").
815        $("[data-product-item] .pName").alignHeight(iMax);
816        $("[data-product-item] .dPrice").alignHeight(iMax);
817        $("[data-product-item] .dBrand").alignHeight(iMax);
818
819    },
820
821    init: (function () {
822        $(function () {
823            obProduct.verticalAlign();
824            obProduct.quantityHover();
825        });
826
827    })()
828
829};
830
831var obBlurer = {
832
833    bind: function () {
834        $("body").on("click touchstart", function (evt) {
835            var target = evt.target;
836            var sBlurer = "";
837
838            //fix for mobile submenu
839            if ($(target).parents(".fancybox-wrap").length || $(target).closest(".fancybox-overlay").length) {
840                return;
841            }
842            //end fix
843
844            if ((Parent = $(target).parents("[data-blurer-parent]:first")).length) {
845                sBlurer = Parent.find("[data-blurer]").attr("data-blurer");
845 //:visible
846            }
847            $("[data-blurer][data-blurer!='" + sBlurer + "']").each(function () {
848                whatHide = $(this);
849                if ($(this).attr("data-blurer-target") == "parent")
850                    whatHide = $(this).parents("[data-blurer-parent]:first");
851                //console.log(whatHide);
852                switch ($(this).attr("data-blurer-type")) {
853                    case ("fadeOut"):
854                    case ("fadeIn"):
855                        whatHide.fadeOut();
856                        break;
857                    case ("active"):
858                    case ("disactive"):
859                        whatHide.removeClass("active");
860                        whatHide.removeClass("hovered");
861                        whatHide.removeClass("selected");
862                        break;
863                    case ("add_class"):
864                        whatHide.addClass($(this).attr("data-blurer-toggle-class"));
865                        break;
866                    default :
867                        whatHide.hide().parents('[data-blurer-parent]:first').removeClass("active");
868                        break;
869                }
870            })
871        });
872        $('body').keypress(function (evt) {
873            if (evt.keyCode == 27)
874                $('body').click();
875        });
876        $.fn.blurerFadeToggle = function (options) {
877            var blurer = $(this).find("[data-blurer]");
878            sBlurer = blurer.attr("data-blurer");
879            blurer.removeAttr("data-blurer");
880            $(this).fadeToggle(function () {
881                blurer.attr("data-blurer", sBlurer)
882            });
883        }
884        $.fn.blurerFadeIn = function (options) {
885            var blurer = $(this).find("[data-blurer]");
886            sBlurer = blurer.attr("data-blurer");
887            blurer.removeAttr("data-blurer");
888            $(this).fadeIn(function () {
889                blurer.attr("data-blurer", sBlurer)
890            });
891        }
892    },
893
894    init: (function () {
895        $(function () {
896            obBlurer.bind();
897        });
898    })()
899};
900
901var obAssociatedT = {
902    bind: function () {
903        var $parent = $("[data-associated]");
904        if ($parent.length) {
905            $parent.find("[data-wrapper]").slick({
906                dots: false,
907                infinite: true,
908                speed: 300,
909                slidesToShow: 6,
910                slidesToScroll: 3,
911                /*adaptiveHeight: true,*/
912                autoplay: true,
913                autoplaySpeed: 7000,
914                prevArrow: '<a href="javascript:void(0)" class="caruser_tovar_prev"></a>',
915                nextArrow: '<a href="javascript:void(0)" class="caruser_tovar_next"></a>',
916                appendArrows: $parent.find("[data-box]")
917            });
918        }
919    },
920
921    init: (function () {
922        $(function () {
923            obAssociatedT.bind();
924        });
925    })()
926};
927
928var obProfile = {
929    parent: false,
930
931
932    getForm: function (self) {
933        'use strict';
934        var $self = $(self);
935        var data = $self.data();
936        var obData = [];
937        if (!!data.oldId) {
938            obData[obData.length] = {name: "PROFILE_ID", value: data.oldId};
939        }
940        if (!!data.id) {
941            obData[obData.length] = {name: "ID", value: data.id};
942        }
943        if (!!data.template) {
944            obData[obData.length] = {name: "TEMPLATE", value: data.template};
945        }
946
947        var $currentDelivery = $("[data-delivery-group].active");
948        if ($currentDelivery.length) {
949            obData[obData.length] = {name: "ADDRESS[TYPE]", value: $currentDelivery.data("delivery-group")};
950        }
951
952        $.ajax({
953            type: "post",
954            data: obData,
955            url: "/local/components/art-fresh/profile.edit/ajax.php",
956            timeout: 30000,
957            beforeSend: function () {
958                $self.addClass("loading");
959            },
960            success: function (data) {
961                $self.removeClass("loading");
962                $.fancybox({
963                    content: $(data).find("[data-profile-address-block]"),
964                    afterShow: function () {
965                        obProfile.bind();
966                    },
967                    helpers: {
968                        overlay: {
969                            locked: false
970                        }
971                    }
972                });
973            }
974        });
975    },
976
977    remove: function (self) {
978        'use strict';
979        var $self = $(self);
980        var iAddressID = $self.data("addressId");
981        var $block = $self.parents("[data-block]");
982        if (window.confirm("Вы уверены что хотите удалить адрес?")) {
983            $.ajax({
984                type: "post",
985                dataType: "json",
986                timeout: 30000,
987                data: {
988                    ID: iAddressID,
989                    sessid: BX.bitrix_sessid()
990                },
991                url: "/local/components/art-fresh/profile.edit/delete.php",
992                beforeSend: function () {
993                    $block.block();
994                },
995                success: function (data) {
996                    if (data.type == "success") {
997
998                        $block.replaceWith($('<div class="dMessage success">' + data.message + '</div>'));
999                        $("[data-address-id='" + data.id + "']").parents("li:first").remove();
1000                        if (typeof obOrder != "undefined") {
1001                            obOrder.submit();
1002                        }
1003                    } else {
1004                        alert(data.message);
1005                        $block.unblock();
1006                    }
1007                }
1008            });
1009        }
1010
1011    },
1012
1013    submit: function (self) {
1014        'use strict';
1015        var $form = $(self);
1016        if (!$form.hasClass("active") && $form.valid()) {
1017            if ($form.data('address-add') == 'Y' && $form.find('input[name="ADDRESS[MKAD]"]').val() == '') {
1018                event.preventDefault();
1019                alert('Выберите адрес вручную');
1020                return false;
1021            }
1022            $.ajax({
1023                type: "post",
1024                url: $form.attr("action"),
1025                data: $form.serializeArray(),
1026                timeout: 30000,
1027                beforeSend: function () {
1028                    $form.addClass("loading");
1029                    $form.block();
1030                },
1031                success: function (data) {
1032                    var $orderForm = $("[data-order-form]");
1033                    var $parent = false;
1034                    $form.unblock();
1035                    if ($orderForm.length) {
1036                        $parent = $orderForm.find("[data-profiles-parent]");
1037                        var $newProfile = $(data).find("[data-address-id]");
1038                        var iNewID = $newProfile.data("addressId");
1039                        var $oldProfile = $parent.find("[data-address-id='" + iNewID + "']");
1040                        if ($oldProfile.length) {
1041                            $oldProfile.replaceWith($newProfile);
1042                        } else {
1043                            $parent.prepend($newProfile);
1044                        }
1045                        $newProfile.trigger("click");
1046                    } else {
1047                        $parent = $(obProfile.parent);
1048                        var $newProfile = $(data).find("[data-address-id]");
1049                        var iNewID = $newProfile.data("addressId");
1050                        var $oldProfile = $parent.find("[data-address-id='" + iNewID + "']");
1051                        if ($oldProfile.length) {
1052                            $oldProfile.replaceWith($newProfile);
1053                        } else {
1054                            var $li = new $("<li></li>");
1055                            $li.append($newProfile);
1056                            $parent.find("[data-add-link]").before($li);
1057                        }
1058                    }
1059
1060
1061                    $form.removeClass("loading");
1062                    $.fancybox.close();
1063
1064                },
1065                error: function () {
1066                    alert("Произошла ошибка");
1067                }
1068            });
1069        }
1070        return false;
1071    },
1072
1073    select: function (self) {
1074
1075        var $orderForm = $("[data-order-form]");
1076        var $self = $(self);
1077        var addressID = $self.data("addressId");
1078        console.log("addressId");
1079        if ($self.hasClass("active")) return;
1080        if ($orderForm.length) {
1081            var $input = $orderForm.find("[name='ADDRESS[ID]']");
1082            var $parent = $self.parents("[data-profiles-parent]");
1083            $parent.find("[data-address-id]").removeClass("active");
1084            $self.addClass("active");
1085            $input.val(addressID);
1086            var fromMkad = $(self).attr('mkad');
1087            $('input[name="ADDRESS[MKAD]"]').val(fromMkad);
1088            $('input[name="initMKAD"]').val(fromMkad);
1089
1090
1091            $.ajax({
1092                type: "post",
1093                url: "/personal_test/system/ajax/ajax-selected-adress.php",
1094                data: {"id": addressID},
1095                timeout: 30000,
1096                beforeSend: function () {
1097
1098                },
1099                success: function (data) {
1100                    if (typeof obOrder != "undefined") obOrder.submit();
1101
1102                },
1103                error: function () {
1104
1105                }
1106            });
1107
1108            // $('#ORDER_FORM').append('<input type="hidden" name="del-select" value="1">');
1109            // if (typeof obOrder != "undefined")  obOrder.submit();
1110
1111        }
1112    },
1113
1114    bind: function () {
1115
1116        $('.dProfileEdit label.has_lift').click(function () {
1117            $(this).find('input').closest('label').removeClass('active');
1118            $(this).find('input:checked').closest('label').addClass('active');
1119        });
1120        obPlaceHolder.bind();
1121    }
1122
1123};
1124
1125var obOverlay = {
1126    bg: false,
1127
1128    show: function (opt) {
1129        if (!!opt) obOverlay.bg.data(opt);
1130        if (obOverlay.bg.length) obOverlay.bg.fadeIn();
1131    },
1132
1133    hide: function () {
1134        if (!obOverlay.bg.length) return;
1135        if (obOverlay.bg.data("hide").length) {
1136            $(obOverlay.bg.data("hide")).fadeOut(300, function () {
1137                if (obOverlay.bg.data("remove") == true) {
1138                    $(obOverlay.bg.data("hide")).remove();
1139                }
1140            });
1141        }
1142
1143        obOverlay.bg.fadeOut(300, function () {
1144            $(this).appendTo($("body"))
1145        });
1146    },
1147
1148    bind: function () {
1149        obOverlay.bg = $("[data-background]");
1150        obOverlay.bg.click(function () {
1151            obOverlay.hide();
1152            $(".popup:visible").hide();
1153            $("[data-over-hide]:visible").hide();
1154        })
1155    },
1156
1157    init: (function () {
1158        $(function () {
1159            obOverlay.bind();
1160        });
1161
1162    })()
1163};
1164
1165var obSmartFilter = {
1166
1167
1168    self: false,
1169
1170    fillTopFilter: function () {
1171        var $parent = $("[data-filter-parent]");
1172        var $filterTop = $("[data-filter-top]");
1173        if ($parent.length && $filterTop.length) {
1174            var arInputs = $parent.find("input[type=checkbox]:checked");
1175            var obData = url.parse(window.location.href, {array: true}).get;
1176            arInputs.each(function () {
1177                var name = $(this).attr("name");
1178                var value = $(this).attr("value");
1179                var text = $(this).data("text");
1180                var obNewGet = [];
1181                for (var i in obData) {
1182                    if (obData[i]) {
1183                        if ((i == name) && (obData[i] == value)) continue;
1184                        obNewGet[i] = obData[i];
1185                    }
1186                }
1187                var sNewPath = url.build({
1188                    get: obNewGet
1189                    //scheme:window.location.protocol,
1190                    //host:window.location.host,
1191                    //path:window.location.pathname
1192                });
1193                var $li = $("<li></li>");
1194                var $span = $("<span>" + text + "</span>");
1195                var $link = $("<a href='" + sNewPath + "' class='delete'></a>");
1196                $span.appendTo($li);
1197                $link.appendTo($li);
1198                $li.appendTo($filterTop);
1199            });
1200
1201
1202        }
1203    },
1204
1205    refresh: function () {
1206        if (typeof (smartFilter) == "object") {
1207            smartFilter.reload($(".smartfilter input:first")[0], true);
1208        }
1209    },
1210
1211    init: (function () {
1212        $(function () {
1213            obSmartFilter.fillTopFilter();
1214            $('#price_max').bind('change', function () {
1215//							console.log('price_max')
1216//							console.log(parseInt($(this).val().replace(" ","")))
1217                slider.noUiSlider.set([null, parseInt($(this).val().replace(" ", ""))])
1218            })
1219            $('#price_min').bind('change', function () {
1220//							console.log('price_max')
1221//							console.log(parseInt($(this).val().replace(" ","")))
1222                slider.noUiSlider.set(parseInt($(this).val().replace(" ", "")), [null])
1223            })
1224        });
1225    })()
1226};
1227
1228var obOrderHelper = {
1229    sendEmail: function (self) {
1230        var $self = $(self);
1231        if ($self.hasClass("loading")) return false;
1232        $.ajax({
1233            //type:"post",
1234            url: $self.attr("href"),
1235            dataType: "json",
1236            timeout: 30000,
1237            beforeSend: function () {
1238                $self.addClass("loading");
1239                //							console.log($self.attr("href"))
1240            },
1241            success: function (data) {
1242                $self.removeClass("loading");
1243                var $newDiv = $("<div class='dSendEmail'/>");
1244                var $message = $("<div class='dMessage " + data.type + "'>" + data.message + "</div>");
1245                $message.appendTo($newDiv);
1246
1247                $.fancybox({
1248                    content: $newDiv,
1249                    afterShow: function () {
1250                        $newDiv.oneTime("2s", function () {
1251                            $.fancybox.close()
1252                        });
1253                    },
1254                    helpers: {
1255                        overlay: {
1256                            locked: false
1257                        }
1258                    }
1259                });
1260            }
1261        });
1262        return false;
1263    }
1264};
1265
1266var obTabber = {
1267    tab: function (self) {
1268        'use strict';
1269        var $self = $(self).parent();
1270        var $parent = $self.parents("[data-parent]");
1271        var $ul = $self.parents("[data-tab-parent]");
1272        var $itemParent = $parent.find("[data-item-parent]");
1273        var tabName = $self.data("tabId");
1274        if (!$self.hasClass("active")) {
1275            $ul.find(".active").removeClass("active");
1276            $self.addClass("active");
1277            $itemParent.find("[data-item-id]").addClass("hidden");
1278            $itemParent.find("[data-item-id='" + tabName + "']").removeClass('hidden');
1279        }
1280    }
1281};
1282
1283var obDocument = {
1284
1285    bind: function () {
1286        $(document).keyup(function (e) {
1287            if (e.keyCode == 27) {
1288                $("body").trigger("click");
1289                obOverlay.hide();
1290            }
1291        });
1292    },
1293
1294    init: (function () {
1295        $(function () {
1296            obDocument.bind();
1297        });
1298    })()
1299};
1300
1301var obGallery = {
1302    data: false,
1303
1304    create: function (index) {
1305        var obData = this.data;
1306        var options = {
1307            big: {
1308                marginBottom: 30,
1309                arrowWidth: 100
1310            },
1311            thumb: {
1312                totalWidth: 95,
1313                totalHeigth: 95,
1314                arrowWidth: 50
1315            }
1316        };
1317
1318
1319        var $gallery = $('<gallery></gallery>').css("display", "none");
1320        var $bigs = $("<bigs></bigs>");
1321        var $thumbs = $("<thumbs></thumbs>");
1322        var iMaxWidth = $(window).width() * 0.8;
1323        var iMaxHeight = $(window).height() * 0.8;
1324
1325        var iMinWidth = (options.thumb.totalWidth) + 50;
1326        var iMinHeight = 200;
1327
1328        var iForBigWidth = iMaxWidth - 2 * options.big.arrowWidth;
1329        var iForBigHeight = iMaxHeight - 2 * options.big.marginBottom - options.thumb.totalHeigth;
1330        var iOriginWidth = -1;
1331        var iOriginHeight = -1;
1332        var iCount = 0;
1333
1334        for (i in obData) {
1335            var obImg = obData[i];
1336            var $smallWrapDiv = $("<div></div>");
1337            var $smallTag = $("<wrap></wrap>");
1338            var $smallImg = $("<img/>");
1339            $smallImg.attr("src", obImg.GALLERY_THUMB.SRC).appendTo($smallTag);
1340            $smallTag.appendTo($smallWrapDiv);
1341
1342            $smallWrapDiv.attr("data-index", i).appendTo($thumbs);
1343
1344
1345            var $bigDiv = $("<div></div>");
1346            var $bigTag = $("<wrap></wrap>");
1347            var $bigImg = $("<img/>");
1348            $bigImg.attr({
1349                "src": obImg.BIG.SRC,
1350                'data-width': obImg.BIG.WIDTH,
1351                'data-height': obImg.BIG.HEIGHT
1352            }).appendTo($bigTag);
1353            $bigTag.appendTo($bigDiv);
1354            $bigDiv.attr("data-index", i).appendTo($bigs);
1355
1356
1357            if (obImg.BIG.WIDTH > iOriginWidth) iOriginWidth = obImg.BIG.WIDTH;
1358            if (obImg.BIG.HEIGHT > iOriginHeight) iOriginHeight = obImg.BIG.HEIGHT;
1359            iCount++;
1360        }
1361        if (iOriginWidth > iForBigWidth) iOriginWidth = iForBigWidth;
1362        if (iOriginHeight > iForBigHeight) iOriginHeight = iForBigHeight;
1363        if (iOriginWidth < iMinWidth) {
1364            iOriginWidth = iMinWidth;
1365        }
1366        if (iOriginHeight < iMinHeight) {
1367            iOriginHeight = iMinHeight;
1368        }
1369
1370        iOriginWidth = IntVal(iOriginWidth);
1371        iOriginHeight = IntVal(iOriginHeight);
1372        $bigs.css({
1373            "width": iOriginWidth + 2 * options.big.arrowWidth,
1374            "height": iOriginHeight
1375
1376        });
1377
1378
1379        fancyOptions = {
1380            afterShow: function () {
1381                $gallery.fadeIn("300");
1382
1383            },
1384            helpers: {
1385                overlay: {
1386                    locked: false
1387                }
1388            },
1389            tpl: {
1390                wrap: '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin popup popup_slider"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',
1391            }
1392        };
1393
1394        if ($bigs.find("wrap").length > 1) {
1395
1396            $bigs.css({
1397                "margin-bottom": options.big.marginBottom,
1398                "padding": "0 " + options.big.arrowWidth + "px"
1399            });
1400            $bigs.find("wrap").css({
1401                "width": iOriginWidth,
1402                "height": iOriginHeight
1403            });
1404            $bigs.find("img").css({
1405                "max-width": iOriginWidth,
1406                "max-height": iOriginHeight
1407            });
1408
1409
1410            $bigs.find("img").each(function () {
1411                var iWidth = IntVal($(this).data("width"));
1412                var iHeight = IntVal($(this).data("height"));
1413                var iPaddingWidth = IntVal(iOriginWidth - iWidth) / 2;
1414                var iPaddingHeight = IntVal(iOriginHeight - iHeight) / 2;
1415                $(this).css({
1416                    "padding-left": iPaddingWidth,
1417                    "padding-right": iPaddingWidth,
1418                    "padding-top": iPaddingHeight
1419                });
1420            });
1421
1422
1423            $bigs.appendTo($gallery);
1424            $("<clear></clear>").appendTo($gallery);
1425            var iThumbsCount = Math.floor((iOriginWidth - 2 * options.thumb.arrowWidth) / options.thumb.totalWidth);
1426            if (iThumbsCount > iCount) iThumbsCount = iCount;
1427
1428
1429            var thumbSlick = {
1430                slidesToShow: iThumbsCount,
1431                slidesToScroll: 1,
1432                swipe: false,
1433                dots: false,
1434                centerMode: false,
1435                prevArrow: '<a href="javascript:void(0)" class="slider_item_prev"></a>',
1436                nextArrow: '<a href="javascript:void(0)" class="slider_item_next"></a>',
1437                focusOnSelect: true
1438            };
1439            $thumbs.css({
1440                width: options.thumb.totalWidth * iThumbsCount + 2 * options.thumb.arrowWidth,
1441                padding: "0 " + options.thumb.arrowWidth + "px",
1442                opacity: 0
1443            });
1444
1445
1446            $thumbs.on("setPosition", function () {
1447                if ($(this).css("opacity") == 0) {
1448                    $(this).animate({opacity: 1}, {
1449                        duration: 300, step: function () {
1450                            $(this).resize();
1451                        }
1452                    }, function () {
1453                        $(this).resize();
1454                    });
1455                }
1456            });
1457            $thumbs.slick(thumbSlick);
1458
1459            $thumbs.slick("slickGoTo", index).slick("setPosition");
1460
1461            var bigsSlick = {
1462                slidesToShow: 1,
1463                slidesToScroll: 1,
1464                asNavFor: $thumbs,
1465                dots: false,
1466                centerMode: false,
1467                prevArrow: '<a href="javascript:void(0)" class="slider_img_prev"></a>',
1468                nextArrow: '<a href="javascript:void(0)" class="slider_img_next"></a>',
1469                focusOnSelect: true
1470            };
1471
1472            $bigs.slick(bigsSlick).on("setPosition", function () {
1473                if ($(this).slick != "undefined") {
1474                    var iCurrent = $(this).slick("slickCurrentSlide");
1475                    $thumbs.find(".slick-slide").removeClass("active");
1476                    $thumbs.find(".slick-slide[data-index='" + iCurrent + "']").addClass("active");
1477                }
1478            }).on("init", function () {
1479                if ($(this).slick != "undefined") {
1480                    var iCurrent = $(this).slick("slickCurrentSlide");
1481                    $thumbs.find(".slick-slide").removeClass("active");
1482                    $thumbs.find(".slick-slide[data-index='" + iCurrent + "']").addClass("active");
1483                }
1484            });
1485            $bigs.slick("slickGoTo", index);
1486            $thumbs.slick("slickSetOption", "asNavFor", "bigs");
1487
1488            $bigs.css({opacity: 0}).on("setPosition", function () {
1489                if ($(this).css("opacity") == 0) $(this).animate({opacity: 1}, 300);
1490            });
1491
1492
1493            $thumbs.appendTo($gallery);
1494            fancyOptions.content = $gallery;
1495        } else fancyOptions.href = $bigs.find("img").attr("src");
1496
1497
1498        $.fancybox(fancyOptions);
1499    }
1500};
1501
1502var obResizer = {
1503
1504    news: function () {
1505        $(window).resize(function () {
1506            $("[data-news-item]").each(function () {
1507                var $img = $(this).find("img");
1508                if ($img.length) {
1509                    var $parent = $(this);
1510                    if ($img[0].naturalWidth > $parent.width()) {
1511                        $img.addClass("max_width");
1512                    } else $img.removeClass("max_width");
1513                }
1514            });
1515        });
1516
1517    },
1518
1519    bind: function () {
1520        obResizer.news();
1521    },
1522
1523    init: (function () {
1524        $(function () {
1525            obResizer.bind();
1526        });
1527
1528    })()
1529};
1530
1531var obResize = {
1532
1533    resizeImages: function (bWidthOnly) {
1534        $("[data-resize-stop]").each(function () {
1535            var $img = $(this).find("img");
1536            var iWidth = $(this).width();
1537            var iHeight = $(this).height();
1538            var $padding = $(this).find("[data-resize-padding]");
1539            if ($padding.length) {
1540                var iPadding = IntVal($padding.css("padding-top"));
1541
1542                if (iHeight > iPadding) iHeight = iPadding;
1543            }
1544
1545            $img.css({"max-width": iWidth + "px", "max-height": iHeight + "px"});
1546
1547
1548            /*if(IntVal($img.data("padding-top")))
1549             {
1550             var $orient = $img.parents("[data-padding-orient]");
1551             iPadding = ($orient.height()-$img.height())/2;
1552             if(iPadding<0) iPadding=0;
1553             $img.css("padding-top",(iPadding))
1554             }*/
1555
1556        });
1557        $("[data-align-height]").each(function () {
1558            var $this = $(this);
1559            var $parent = $this.parents("[data-align-parent]:first");
1560            if ($parent.length) {
1561                var iParentHeight = $parent.outerHeight();
1562                $this.height(iParentHeight);
1563            }
1564        });
1565        $("[data-align-width]").each(function () {
1566            var $this = $(this);
1567            var $parent = $this.parents("[data-align-parent]:first");
1568            if ($parent.length) {
1569                var iParentWidth = $parent.outerWidth();
1570                $this.width(iParentWidth);
1571            }
1572        });
1573
1574    },
1575    bind: function () {
1576        $(window).resize($.debounce(250, function () {
1577            obResize.resizeImages(true)
1578        }));
1579        $(window).trigger("resize");
1580    },
1581
1582    init: (function () {
1583        $(function () {
1584            obResize.bind();
1585        });
1586    })()
1587};
1588
1589var obLazyLoad = {
1590    instance: false,
1591
1592    reload: function () {
1593        obLazyLoad.fix();
1594    },
1595
1596    processImage: function ($self) {
1597        $self.addClass("loading");
1598        var tmpImg = new Image();
1599
1600        tmpImg.onload = obLazyLoad.imageReady($self);
1601
1602        if ($self.hasAttr("data-src")) {
1603            tmpImg.src = $self.attr('data-src');
1604        }
1605
1606    },
1607
1608    imageReady: function ($self) {
1609        $self.attr("src", $self.attr("data-lazy-src")).show().removeAttr("data-lazy-src").removeClass("loading").addClass("initialized");
1610
1611    },
1612
1613    fix: function () {
1614        $("body").stopTime().everyTime("300ms", function () {
1615            /* $(window).trigger("resize");
1616             $(window).trigger("scroll"); */
1617        });
1618
1619    },
1620
1621    init: (function () {
1622
1623        $(window).scroll(function () {
1624            $("img[data-lazy-src]:not(.initialized):not(.loading)").each(function () {
1625                var $self = $(this);
1626                if ($self.inView()) {
1627                    obLazyLoad.processImage($self);
1628                }
1629            });
1630
1631        });
1632
1633        $(function () {
1634            $(document).ajaxStop(function () {
1635                obLazyLoad.fix();
1636            });
1637            obLazyLoad.fix();
1638        });
1639    })()
1640};
1641
1642var obURLHelper = {
1643
1644    specialCharsDecode: function (string, quoteStyle) { // eslint-disable-line camelcase
1645        //       discuss at: http://locutus.io/php/htmlspecialchars_decode/
1646        //      original by: Mirek Slugen
1647        //      improved by: Kevin van Zonneveld (http://kvz.io)
1648        //      bugfixed by: Mateusz "loonquawl" Zalega
1649        //      bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
1650        //      bugfixed by: Brett Zamir (http://brett-zamir.me)
1651        //      bugfixed by: Brett Zamir (http://brett-zamir.me)
1652        //         input by: ReverseSyntax
1653        //         input by: Slawomir Kaniecki
1654        //         input by: Scott Cariss
1655        //         input by: Francois
1656        //         input by: Ratheous
1657        //         input by: Mailfaker (http://www.weedem.fr/)
1658        //       revised by: Kevin van Zonneveld (http://kvz.io)
1659        // reimplemented by: Brett Zamir (http://brett-zamir.me)
1660        //        example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES')
1661        //        returns 1: '<p>this -> &quot;</p>'
1662        //        example 2: htmlspecialchars_decode("&amp;quot;")
1663        //        returns 2: '&quot;'
1664
1665        var optTemp = 0;
1666        var i = 0;
1667        var noquotes = false;
1668
1669        if (typeof quoteStyle === 'undefined') {
1670            quoteStyle = 2
1671        }
1672        string = string.toString()
1673            .replace(/&lt;/g, '<')
1674            .replace(/&gt;/g, '>');
1675        var OPTS = {
1676            'ENT_NOQUOTES': 0,
1677            'ENT_HTML_QUOTE_SINGLE': 1,
1678            'ENT_HTML_QUOTE_DOUBLE': 2,
1679            'ENT_COMPAT': 2,
1680            'ENT_QUOTES': 3,
1681            'ENT_IGNORE': 4
1682        };
1683        if (quoteStyle === 0) {
1684            noquotes = true
1685        }
1686        if (typeof quoteStyle !== 'number') {
1687            // Allow for a single string or an array of string flags
1688            quoteStyle = [].concat(quoteStyle)
1689            for (i = 0; i < quoteStyle.length; i++) {
1690                // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
1691                if (OPTS[quoteStyle[i]] === 0) {
1692                    noquotes = true
1693                } else if (OPTS[quoteStyle[i]]) {
1694                    optTemp = optTemp | OPTS[quoteStyle[i]]
1695                }
1696            }
1697            quoteStyle = optTemp
1698        }
1699        if (quoteStyle & OPTS.ENT_HTML_QUOTE_SINGLE) {
1700            // PHP doesn't currently escape if more than one 0, but it should:
1701            string = string.replace(/&#0*39;/g, "'")
1702            // This would also be useful here, but not a part of PHP:
1703            // string = string.replace(/&apos;|&#x0*27;/g, "'");
1704        }
1705        if (!noquotes) {
1706            string = string.replace(/&quot;/g, '"')
1707        }
1708        // Put this in last place to avoid escape being double-decoded
1709        string = string.replace(/&amp;/g, '&')
1710
1711        return string
1712    },
1713
1714    processURL: function (opts) {
1715
1716        var sURL = false;
1717        var arExceptions = [];
1718        var arAddParams = [];
1719        var bPushState = false;
1720        var bCatalogAjax = false;
1721        if (!!opts.url) sURL = opts.url;
1722        if (!!opts.exceptions) arExceptions = opts.exceptions;
1723        if (!!opts.addParams) arAddParams = opts.addParams;
1724        if (!!opts.pushState) bPushState = opts.pushState;
1725        if (!!opts.catalogAjax) bCatalogAjax = opts.catalogAjax;
1726
1727
1728        var sCurrentURL = window.location.href;
1729
1730        if (!sURL) {
1731            sURL = sCurrentURL;
1732        }
1733
1734
1735        var sCleanURL = url.parse(sURL, {array: true}).path;
1736
1737        var arAvailableParams = [
1738            "page",
1739            "sort",
1740            "size"
1741        ];
1742        var arDiff = [];
1743
1744        var obData = url.parse(sCurrentURL, {array: true}).get;
1745
1746        var obNewGet = [];
1747
1748        for (var i in obData) {
1749            if ($.inArray(i, arExceptions) >= 0) {
1750                continue;
1751            }
1752            if (obData[i]) {
1753                obNewGet[i] = obData[i];
1754            }
1755        }
1756
1757
1758        if (!!arAddParams && arAddParams != []) {
1759            for (i in arAddParams) {
1760                obNewGet[i] = arAddParams[i];
1761            }
1762        }
1763
1764        var sNewPath = url.build({
1765            path: sCleanURL,
1766            get: obNewGet
1767        });
1768
1769        if (bPushState && (sNewPath != window.location.pathname + window.location.search)) history.replaceState("", document.title, sNewPath.length ? sNewPath : window.location.pathname);
1770
1771        if (bCatalogAjax) obSection.catalogAjax();
1772
1773        return sNewPath;
1774    },
1775
1776    setSeo: function (obSeo) {
1777        if(obSeo.NAME){
1778            if(obSeo.TITLE!=' купить с доставкой в Москве | Мир Красок'){
1779                document.title = this.specialCharsDecode(obSeo.TITLE);
1780            }
1781            $("meta[name='keywords']").attr("content", this.specialCharsDecode(obSeo.KEYWORDS));
1782            $("meta[name='description']").attr("content", this.specialCharsDecode(obSeo.DESCRIPTION));
1783            $("h1").text(this.specialCharsDecode(obSeo.NAME));
1784        }
1785    }
1786
1787};
1788
1789var obMenu = {
1790
1791    toggle: function (self) {
1792        //	 console.log('self')
1793        //	 console.log(self)
1794        //	 console.log('obMenu.scroll_pos_y')
1795        //	 console.log(obMenu.scroll_pos_y)
1796
1797        this_f = this;
1798        if ($("#main").children().attr("menu") == 'true') {
1799            $("#main").css("position", "fixed");
1800            $.scrollTo('.navigation');
1801            $('.sidebar-menu').show();
1802            $("#main").children().animate({left: "0px"}, 300, function () {
1803                $("#main").children().attr("menu", "false");
1804                $('.sidebar-menu').css("z-index", "100000");
1805
1806            });
1807        } else {
1808            $("#main").css("position", "relative");
1809            $('.sidebar-menu').css("z-index", "0");
1810            $("#main").children().animate({left: "0px"}, 300, function () {
1811                $("#main").children().attr("menu", "true");
1812                $('.sidebar-menu').hide();
1813
1814                //		 console.log('scroll_pos_y')
1815                //		 console.log(this_f.scroll_pos_y)
1816                window.scrollTo(0, this_f.scroll_pos_y)
1817
1818            });
1819        }
1820
1821    },
1822
1823    bind: function () {
1824
1825    },
1826
1827    init: (function () {
1828        $(function () {
1829            obMenu.bind();
1830        });
1831    })()
1832};
1833
1834var obSKUShops = {
1835    map: false,
1836    mapObject: false,
1837    json: false,
1838    polygons: [],
1839    points: [],
1840    temp: false,
1841    geoPoint: false,
1842    currentPlace: false,
1843    nearestCount: 10,
1844
1845
1846    addPolygons: function () {
1847        for (i in this.json) {
1848            var polygon = this.json[i];
1849            var points = polygon.UF_POINTS;
1850            var sProperties = polygon.UF_POLY_STYLE;
1851            var properties = sProperties.split(";");
1852
1853            var points = [];
1854            for (j in polygon.UF_POINTS) {
1855                var sPoint = polygon.UF_POINTS[j];
1856                var arPoint = sPoint.split(",");
1857                points.push([arPoint[1], arPoint[0]]);
1858            }
1859
1860
1861            this.polygons[polygon.ID] = new ymaps.Polygon([
1862                    points, [],
1863                ],
1864                {
1865                    hintContent: ""
1866                },
1867                {
1868                    hasHint: 0,
1869                    hasBalloon: 0,
1870                    fill: properties[0],
1871                    outline: properties[1],
1872                    strokeWidth: properties[2],
1873                    strokeColor: properties[3],
1874                    fillColor: properties[4]
1875                });
1876            this.map.geoObjects.add(this.polygons[polygon.ID]);
1877
1878        }
1879    },
1880
1881    addPoints: function () {
1882        for (i in this.json) {
1883            var region = this.json[i];
1884            for (j in region.CHILDS) {
1885                var shop = region.CHILDS[j];
1886                var sCoords = shop.UF_POINT;
1887                var arPoint = sCoords.split(",");
1888                var point = [arPoint[1], arPoint[0]];
1889                var balloon = new ymaps.Balloon(this.map, null, {
1890                    maxWidth: "1000px",
1891                    minWidth: "1000px"
1892                });
1893                var iconBaloon = "/i/icons/map/mk_spot.svg";
1894                var amount = 0;
1895
1896                var balloonContent = "";
1897
1898                $.each(shop.ELEMENTS, function (index, value) {
1899                    amount += value.AMOUNT * 1;
1900                    if (value.TT_TYPE != undefined) {
1901                        if (value.TT_TYPE == "СЦТ") {
1902                            iconBaloon = "/i/icons/map/t_spot.svg";
1903                            balloonContent = '';
1904                        } else {
1905                            balloonContent = "<div style='margin-left:20px; width:26px; background-color:#fff;font-size:8px;padding:2px;'>" + amount + " шт.</div>";
1906                        }
1907                    }
1908                });
1909
1910
1911                var options = {
1912                    iconLayout: 'default#imageWithContent',
1913                    //                 iconLayout:'default#image',
1914                    hideIconOnBalloonOpen: false,
1915                    iconImageHref: iconBaloon,
1916                    iconImageSize: [30, 40],
1917                    iconImageOffset: [-24, -24],
1918                    zIndex: IntVal(shop.UF_MAIN) ? 2 : 1
1919                };
1920
1921                obSKUShops.points[shop.ID] = new ymaps.Placemark(point, {
1922                    balloonContent: shop.HTML,
1923                    balloon: balloon,
1924                    iconContent: balloonContent
1925                }, options);
1926
1927                obSKUShops.points[shop.ID].events.add("balloonopen", function (a, b, c) {
1928                    obSKUShops.temp = a;
1929                    var props = a.originalEvent.currentTarget.properties;
1930                    var html = "<div>" + props.get("balloonContent") + "</div>";
1931                    var $html = $(html);
1932                    var iCurrentSectionID = IntVal(ExtGetCookie("MY_SHOP"));
1933                    var $link = $html.find("[data-shop]");
1934                    if ($link.data("shop") == iCurrentSectionID) {
1935                        $link.addClass("active");
1936                    } else $link.removeClass("active");
1937                    props.set("balloonContent", $html.html());
1938                });
1939                this.map.geoObjects.add(this.points[shop.ID]);
1940            }
1941        }
1942    },
1943
1944    showBubble: function (iSectionID) {
1945        if (!!iSectionID) {
1946            $(window).scrollTo(obSKUShops.mapObject, 500);
1947            obSKUShops.points[iSectionID].events.fire("click")
1948        }
1949    },
1950
1951    bind: function () {
1952        obSKUShops.mapObject = $("[data-map]");
1953        obSKUShops.map = new ymaps.Map(obSKUShops.mapObject[0], {
1954            center: [55.763, 37.62],
1955            zoom: 9
1956        });
1957
1958        obSKUShops.map.behaviors.enable('scrollZoom');
1959        obSKUShops.addPolygons();
1960        obSKUShops.addPoints();
1961    },
1962
1963
1964    init: (function () {
1965
1966        $(function () {
1967            //ymaps.ready(obSKUShops.bind);
1968        });
1969    })()
1970};
1971
1972var obDetailProduct = {
1973
1974    sliderValue: 0,
1975
1976    slider: false,
1977
1978    popup: function (iElementID) {
1979        console.log('iElementID', iElementID)
1980        if ($(window).width() < 400) return true;
1981        $.fancybox({
1982            type: 'ajax',
1983            href: "/local/components/art-fresh/catalog.element/popup.php?ELEMENT_ID=" + iElementID,
1984            /*autoHeight : true,
1985             maxWidth    : "90%",
1986             height   : "auto",
1987             autoDimensions: true,
1988             fitToView: true,*/
1989            helpers: {
1990                overlay: {
1991                    locked: false
1992                }
1993            },
1994            afterShow: function () {
1995                console.log('asdasdasdas')
1996                var $parent = $(".fancybox-inner");
1997                $parent.css("overflow", "hidden");
1998                //var iHeight = $parent.height();
1999                var iHeight = $(window).height() * 0.8;
2000                var iTopHeight = 50 + $(".product-filter").height();
2001                var iBottomHeight = IntVal($(".item").css("padding-bottom"));
2002                var $skuItems = $parent.find("[data-sku-items]");
2003                if ($skuItems.length) {
2004                    $skuItems.css("max-height", iHeight - iTopHeight - iBottomHeight);
2005                }
2006                obDetailProduct.bind();
2007                var iPriceTotal = $("[data-rrc-price]:first").data("rrc-price");
2008                obDetailProduct.slider = false;
2009                //		if(FloatVal(iPriceTotal) == 0) iPriceTotal = 500
2010                obDetailProduct.setSlider(FloatVal(iPriceTotal));
2011                $(window).resize();
2012            }
2013        });
2014        return false;
2015    },
2016
2017    showQuantity: function (iSKUID) {
2018        ///return false;
2019        let script = document.createElement('script');
2020        script.src = "https://api-maps.yandex.ru/2.1/?apikey=748df251-82c9-4a42-bb3a-67c975e98c86&lang=ru_RU";
2021        document.head.append(script);
2022
2023        script.onload = function () {
2024            $.fancybox({
2025                type: 'ajax',
2026                href: "/local/components/mirkrasok/shop.list_order.n153/ajax.php?ID=" + iSKUID,
2027                maxWidth: "100%",
2028                autoDimensions: false,
2029                padding: 0,
2030                /*autoHeight : true,
2031
2032                 height   : "auto",
2033
2034                 fitToView: true,*/
2035                helpers: {
2036                    overlay: {
2037                        locked: false
2038                    }
2039                },
2040                afterShow: function () {
2041                    obSKUShops.bind();
2042                }
2043            });
2044        }
2045    },
2046    showQuantityRezerv: function (iSKUID) {
2047        ///return false;
2048        let script = document.createElement('script');
2049        let count_rezerv = $('[data-quantity-rezerv]').val();
2050        script.src = "https://api-maps.yandex.ru/2.1/?apikey=748df251-82c9-4a42-bb3a-67c975e98c86&lang=ru_RU";
2051        document.head.append(script);
2052
2053        script.onload = function () {
2054            $.fancybox({
2055                type: 'ajax',
2056                href: "/local/components/mirkrasok/shop.list_order.n153/ajax.php?ID=" + iSKUID + "&qnt=" + count_rezerv,
2057                maxWidth: "100%",
2058                autoDimensions: false,
2059                padding: 0,
2060                /*autoHeight : true,
2061
2062                 height   : "auto",
2063
2064                 fitToView: true,*/
2065                helpers: {
2066                    overlay: {
2067                        locked: false
2068                    }
2069                },
2070                afterShow: function () {
2071                    obSKUShops.bind();
2072                }
2073            });
2074        }
2075    },
2076    showQuantitySCT: function (iSKUID) {
2077        let script = document.createElement('script');
2078        script.src = "https://api-maps.yandex.ru/2.1/?apikey=748df251-82c9-4a42-bb3a-67c975e98c86&lang=ru_RU";
2079        document.head.append(script);
2080
2081        var qnt = $('[data-quantity-rezerv]').val();
2082        script.onload = function () {
2083            $.fancybox({
2084                type: 'ajax',
2085                href: "/local/components/mirkrasok/shop.list_order.n153/ajax.php?ID=" + iSKUID + "&shops=СЦТ&qnt=" + qnt,
2086                maxWidth: "100%",
2087                autoDimensions: false,
2088                padding: 0,
2089                /*autoHeight : true,
2090
2091                 height   : "auto",
2092
2093                 fitToView: true,*/
2094                helpers: {
2095                    overlay: {
2096                        locked: false
2097                    }
2098                },
2099                afterShow: function () {
2100                    obSKUShops.bind();
2101                }
2102            });
2103        }
2104    },
2105
2106    selectColor: function (self, e) {
2107        $(self).toggleClass("active");
2108        //  try{
2109        //	 }catch(err){
2110        //		 console.log(err)
2111        //	 }
2112        this.processColors();
2113
2114    },
2115
2116    selectSize: function (self) {
2117        console.log(self)
2118        $(self).toggleClass("active");
2119        this.processSizes();
2120        /* скрол к фильтрам */
2121        $('body, html').animate({scrollTop: $('.volume').offset().top});
2122
2123    },
2124
2125    processColors: function () {
2126        var $product = $("[data-product-detail]");
2127        var $selects = $product.find("[data-color-id].active");
2128
2129        var arColors = [];
2130        $selects.each(function () {
2131            arColors.push($(this).data("color-id"));
2132        });
2133
2134        var $divs = $product.find("[data-volume-group][data-volume]");
2135
2136
2137        $divs.each(function () {
2138            var $div = $(this);
2139
2140            var $toggler = $div.find("[data-toggler-parent]");
2141            var $skuItems = $div.find("[data-sku-id]");
2142            if (arColors.length) {
2143                $toggler.addClass("hidden");
2144                $skuItems.removeClass("hidden");
2145            } else {
2146                var $items = $div.find("[data-hidden]");
2147
2148                $items.addClass("hidden");
2149                if ($items.length) {
2150                    $toggler.find("[data-toggler]:first").removeClass("hidden");
2151                    $toggler.find("[data-toggler]:last").addClass("hidden");
2152                    $toggler.removeClass("hidden");
2153                }
2154
2155            }
2156
2157            $skuItems.each(function () {
2158                var $this = $(this);
2159                var color = $this.data("color-id");
2160
2161                if (arColors.length && ($.inArray(color, arColors) < 0)) {
2162                    $this.addClass("hidden");
2163                } else $this.removeClass("hidden");
2164            });
2165
2166        });
2167
2168    },
2169
2170    processSizes: function () {
2171        var $product = $("[data-product-detail]");
2172        var $selects = $product.find("[data-volume-select-parent] [data-volume].active");
2173
2174        var arSizes = [];
2175        console.log([$(this)])
2176        $selects.each(function () {
2177            arSizes.push($(this).data("volume"));
2178        });
2179
2180        var $divs = $product.find("[data-volume-group]");
2181        $divs.each(function () {
2182            var $div = $(this);
2183            var size = $div.data("volume");
2184
2185            if (arSizes.length && ($.inArray(size, arSizes) < 0)) {
2186                $div.addClass("hidden");
2187            } else $div.removeClass("hidden");
2188        });
2189
2190    },
2191
2192    imgClick: function (self) {
2193        var $self = $(self);
2194        /*var $parent=$self.parents("[data-gallery]:first");
2195         var index=$self.data("index");
2196         var data=$parent.data("gallery");
2197         obGallery.data=data;
2198         obGallery.create(index);*/
2199        var src = $self.data("image");
2200        $.fancybox({href: src})
2201    },
2202
2203    changeTab: function (self) {
2204        var $select = $(self);
2205        var $option = $select.find("option:selected");
2206        var $parent = $select.parents("[data-product-tabs]");
2207        var $link = $parent.find("[data-tab='" + $option.data("tab") + "']");
2208        if ($link.length) $link.trigger("click");
2209
2210
2211    },
2212
2213    selectTab: function (self, bScrollTo) {
2214
2215
2216        var $self = $(self);
2217        var sTab = $self.data("tab");
2218
2219        var $parent = $("[data-product-tabs]");
2220        var $currentTab = $parent.find("[data-tab='" + sTab + "']");
2221
2222        var $tabs = $parent.find("[data-tab]");
2223        if (!$currentTab.hasClass("active")) {
2224            $tabs.removeClass("active");
2225            $currentTab.addClass("active");
2226
2227            $parent.find("[data-tab-data]").addClass("hidden");
2228            let cont = $parent.find("[data-tab-data='" + sTab + "']");
2229            cont.removeClass("hidden");
2230            if (sTab === 'RASHOD' && !cont.hasClass('js--loaded')) {
2231                $.get('?get-rashod-values=Y', function (html) {
2232                    cont.addClass('js--loaded').html(html);
2233                });
2234            }
2235            $parent.find("[data-select] option[data-value='" + sTab + "']").attr("selected", "y");
2236        }
2237
2238
2239        if (!!bScrollTo) {
2240            var top = $("[data-product-tabs]").offset().top - 250;
2241            //	console.log(top);
2242            $(window).scrollTo(top, 500);
2243        }
2244
2245    },
2246
2247    toggleItems: function (self) {
2248        var $self = $(self);
2249        var $parent = $self.parents("[data-parent]:first");
2250        var $sliderParent = $parent.parents("[data-slide-parent]");
2251        var $hiddens = $sliderParent.find("[data-hidden]");
2252        $hiddens.toggleClass("hidden");
2253        $parent.find("[data-toggler]").toggleClass("hidden");
2254
2255    },
2256
2257    toggleItemsGlobal: function (self) {
2258        var $self = $(self);
2259        var $parent = $self.parents("[data-volume-group]");
2260        var $items = $parent.find("[data-slide-parent], [data-global-toggler]");
2261        $items.toggleClass("hidden");
2262
2263    },
2264
2265    setSlider: function (iValue) {
2266        if (!!iValue) obDetailProduct.sliderValue = iValue;
2267//				console.log('obDetailProduct.sliderValue')
2268//				console.log(obDetailProduct.sliderValue)
2269        if (obDetailProduct.sliderValue == 0) obDetailProduct.sliderValue = 1000
2270        if ((!obDetailProduct.slider) || (!obDetailProduct.slider.length)) {
2271            obDetailProduct.slider = $("[data-item-price]");
2272
2273            if (obDetailProduct.slider.length) {
2274
2275                obDetailProduct.slider.each(function () {
2276                    if (typeof this.noUiSlider != "undefined") {
2277                        this.noUiSlider.destroy();
2278                    }
2279                    noUiSlider.create(this, {
2280                        start: obDetailProduct.sliderValue,
2281                        behaviour: 'none',
2282
2283                        range: {
2284                            "min": RRC_FROM,
2285                            "25%": MRC_FROM,
2286                            "50%": PRC_FROM,
2287                            'max': BOC1_FROM
2288                        }
2289                    });
2290                });
2291
2292
2293            }
2294
2295        } else {
2296            obDetailProduct.slider[0].noUiSlider.set(obDetailProduct.sliderValue);
2297        }
2298
2299
2300    },
2301
2302    syncHeader: function () {
2303        var $self = $("[data-price-header]");
2304        if ($self.length) {
2305            $self.each(function () {
2306                var $this = $(this);
2307                var $parent = $this.parents("[data-product-id]");
2308                var $orderTo = $parent.find("[data-price-id]:first");
2309
2310                if ($orderTo.length) {
2311                    var offsetLeft = $orderTo.position().left - 15;
2312                    $this.css("left", offsetLeft).removeClass("hidden");
2313                }
2314
2315                var $header = $this.parents("[data-sync-header]:first");
2316                if ($header.length) {
2317                    var iOffset = $header.offset().top + $header.height();
2318                    var $offseter = $header.find("[data-item-price]");
2319                    var iOffset2 = $offseter.offset().top + $offseter.height() / 2;
2320                    //console.log(iOffset, iOffset2);
2321                    $this.css("top", iOffset - iOffset2);
2322                }
2323
2324            });
2325
2326        }
2327    },
2328
2329    syncNameHeight: function () {
2330        let arAlignment = [];
2331        let maxHeigt = 0;
2332
2333        $(".oboi-element-name").each(function (index, element) {
2334
2335            maxHeigt = Math.max(maxHeigt, $(this).height());
2336            arAlignment.push(this)
2337            if (arAlignment.length > 2) {
2338                arAlignment.forEach(function (item) {
2339                    $(item).css({"height": maxHeigt})
2340                })
2341                maxHeigt = 0;
2342                arAlignment = [];
2343            }
2344        })
2345    },
2346
2347    hcInit: function (a, b) {
2348        //console.log(a,b);
2349        window.setTimeout(function () {
2350            $(".hc__ht").remove();
2351            $("[data-hc-id]").each(function () {
2352                $(this).removeAttr("data-hc-id");
2353            });
2354        }, 100);
2355
2356    },
2357
2358    bind: function () {
2359        $(window).resize($.debounce(250, function () {
2360            obDetailProduct.syncHeader()
2361        }));
2362        obBasket.setPriceType();
2363        this.syncHeader();
2364        this.syncNameHeight();
2365    },
2366
2367    init: (function () {
2368        $(function () {
2369            obDetailProduct.bind();
2370        });
2371    })()
2372
2373};
2374
2375var obTooltiper = {
2376    tooltipster:null,
2377    bind: function () {
2378        this.tooltipster=$("[data-tooltipser]:not(.tooltipstered)").tooltipster({
2379            animation: 'fade',
2380            delay: 100,
2381            theme: 'tooltipster-light',
2382            touchDevices: false,
2383            trigger: 'hover',
2384            maxWidth: 350,
2385            /*contentAsHTML: true,*/
2386        });
2387    },
2388    init: (function () {
2389        $(document).ajaxStop(function () {
2390            obTooltiper.bind();
2391        });
2392        $(function () {
2393            obTooltiper.bind();
2394        });
2395    })()
2396};
2397
2398var obFilesHelper = {
2399
2400    bind: function () {
2401        $('[data-file]').each(function () {
2402            var $this = $(this);
2403            $this.bootstrapFileInput();
2404            $this.trigger("change");
2405        });
2406
2407    },
2408
2409    init: (function () {
2410        $(function () {
2411            obFilesHelper.bind();
2412        });
2413    })()
2414};
2415
2416var obPayment = {
2417    confirmPayCard: function (self) {
2418        var $self = $(self);
2419        if ($self.hasClass("active")) {
2420            return true;
2421        } else {
2422            //window.alert("Вам необходимо подтвердить правильность заказа");
2423            return false;
2424        }
2425
2426    },
2427
2428    changePayCard: function (self) {
2429        var $self = $(self);
2430        var $parent = $self.parents("[data-parent]:first");
2431        var $label = $parent.find("[data-label]");
2432        var $link = $parent.find("[data-paylink]");
2433        $self.oneTime('50ms', function () {
2434            if ($self.prop("checked")) {
2435                $label.addClass("active");
2436                $link.addClass("active");
2437            } else {
2438                $label.removeClass("active");
2439                $link.removeClass("active");
2440            }
2441            //console.log($self.prop("checked"));
2442        });
2443
2444
2445    }
2446};
2447
2448var obWebForms = {
2449
2450    submit: function () {
2451
2452        var $form = $(this);
2453        if ($form.valid()) {
2454            $form.append("<input name='web_form_submit' type='hidden' value='1'/>");
2455            var obData = $form.serialize();
2456            var $parent = $form.parent();
2457
2458
2459            $.ajax({
2460                type: "post",
2461                url: $form.attr("action"),
2462                data: obData,
2463                dataType: "json",
2464                timeout: 30000,
2465                beforeSend: function () {
2466                    $parent.addClass("loading");
2467                    ///								console.log('form ready to send ')
2468
2469                },
2470                success: function (data) {
2471                    $parent.removeClass("loading");
2472                    var $message = $parent.find(".dMessage");
2473                    if ($message.length) $message.remove();
2474                    $message = $("<div class='dMessage " + data.type + "'>" + data.text + "</div>");
2475                    if (data.type == "success") {
2476                        //							console.log('form ok')
2477                        $parent.empty().append($message);
2478                        $(window).scrollTo($message, 20);
2479                    } else {
2480                        //							console.log('form fucked')
2481                        $parent.find("input[type=submit]").before($message);
2482                    }
2483                }
2484
2485            });
2486        }
2487        return false;
2488    },
2489
2490    bind: function () {
2491        var $wf = $(".web-form");
2492        $wf.each(function () {
2493            $(this).find("form").on("submit", obWebForms.submit);
2494            var $radio = $(this).find("input[name*='form_radio_']");
2495            $(this).find("input[type=checkbox]").next().addClass("label-checkbox");
2496            var groups = {
2497                radio: []
2498            };
2499            $radio.each(function () {
2500                var name = $(this).attr("name");
2501                var regex = new RegExp("form_radio_(.+)$");
2502                if (regex.test(name)) {
2503                    var arMatch = name.match(regex);
2504                    var code = arMatch[1];
2505                    if ($.inArray(code, groups.radio) != 0) groups.radio.push(code);
2506                }
2507            });
2508
2509            for (i in groups.radio) {
2510                var code = groups.radio[i];
2511                $wf.find("label[for*='" + code + "']").addClass("label-radio");
2512                $('input[name="form_radio_' + code + '"]').closest('label').next().removeClass('active');
2513                $('input[name="form_radio_' + code + '"]:checked').closest('label').next().addClass('active');
2514                $('input[name="form_radio_' + code + '"]').each(function () {
2515                    var $this = $(this);
2516                    $this.change(function () {
2517                        $('input[name="form_radio_' + code + '"]').closest('label').next().removeClass("active");
2518                        var $label = $this.closest('label').next();
2519                        if ($this.is(":checked")) {
2520                            $label.addClass('active');
2521                        } else {
2522                            $label.removeClass("active");
2523                        }
2524
2525                    });
2526                });
2527            }
2528            var $select = $(this).find("select");
2529            $select.each(function () {
2530                var $this = $(this);
2531                var $div = $("<div class='select-wrapper'></div>");
2532                $this.before($div);
2533                $div.append($this);
2534            });
2535
2536            /*
2537             */
2538        });
2539    },
2540
2541    init: (function () {
2542        $(function () {
2543            obWebForms.bind();
2544        });
2545    })()
2546};
2547
2548var obRegister = {
2549    card: function (self) {
2550        $.fancybox({
2551            type: "ajax",
2552            href: "/local/components/art-fresh/card.verify/ajax.php?template=register"
2553        });
2554    },
2555
2556    submit: function (self) {
2557        var $form = $(self);
2558        $form.validate({
2559            rules: {
2560                "REGISTER[PERSONAL_PHONE]": {
2561                    phone: 10
2562                },
2563                "REGISTER[CONFIRM_PASSWORD]": {
2564                    equalTo: "#registerPassword"
2565                }
2566
2567            }
2568        });
2569        if ($form.valid() && !$form.hasClass("loading")) {
2570            var $sess = $("<input type='hidden' name='sessid' value='" + BX.bitrix_sessid() + "'/>");
2571
2572            //$sess.appendTo($form);
2573            var ingateTarget = "register";
2574            $.ajax({
2575                type: "post",
2576                url: $form.attr("action"),
2577                dataType: "json",
2578                timeout: 30000,
2579                data: $form.serialize(),
2580                beforeSend: function () {
2581                    $form.addClass("loading");
2582                },
2583                success: function (data) {
2584                    $form.removeClass("loading");
2585                    var $message = $form.find(".dMessage");
2586                    if ($message.length) $message.remove();
2587                    $message = $("<div class='dMessage " + data.type + "'>" + data.text + "</div>");
2588                    if (data.type == "success") {
2589                        window.location.href = "/personal/card";
2590                        $form.empty().append($message);
2591                        $(window).scrollTo($message, 300);
2592                        ym(7500958, 'reachGoal', ingateTarget);
2593
2594                        var ee = setInterval(function () {
2595                            if (typeof window.ym != 'undefined') {
2596                                ym(7500958, 'reachGoal', 'registration_complete');
2597                                console.log('registration_complete');
2598                                clearInterval(ee);
2599                            } else {
2600                                console.log('Метрика не инициализирована');
2601                            }
2602                        }, 500);
2603
2604                    } else {
2605                        $form.find("[data-button]").before($message);
2606                    }
2607                }
2608            });
2609        }
2610
2611        return false;
2612    },
2613
2614    show: function () {
2615        $.fancybox({
2616            type: "ajax",
2617            href: "/local/components/art-fresh/main.register/ajax.php",
2618            afterShow: function () {
2619                obPlaceHolder.bind();
2620            }
2621        });
2622    }
2623};
2624
2625var obCard = {
2626
2627    submit: function (self) {
2628        var $form = $(self);
2629        $.ajax({
2630            type: "post",
2631            data: $form.serializeArray(),
2632            url: "/local/components/art-fresh/card.verify/ajax.php",
2633            beforeSend: function () {
2634                $form.addClass("loading").block();
2635            },
2636            success: function (data) {
2637                var response = false;
2638                try {
2639                    response = jQuery.parseJSON(data);
2640                } catch (e) {
2641
2642                }
2643
2644                if (typeof response == 'object') {
2645                    // It is JSON
2646                    $form.replaceWith($(response.template).find("form"));
2647                    obPlaceHolder.bind();
2648                    if (!!response.card_data) {
2649                        var $data = response.card_data;
2650                        var $link = $("[data-has-card]");
2651                        var cardNumber = $data.UF_CARD_NUMBER;
2652                        if ($link.length) $link.replaceWith("Номер карты: " + cardNumber);
2653                        var arFio = $data.UF_NAME.trim().replace(/[ ]+/g, " ").split(" ");
2654                        var $input = $("[name='REGISTER[LAST_NAME]']");
2655                        if ($input.length && arFio[0]) $input.val(arFio[0]).addClass("success");
2656                        var $input = $("[name='REGISTER[FIRST_NAME]']");
2657                        if ($input.length && arFio[1]) $input.val(arFio[1]).addClass("success");
2658                        var $input = $("[name='REGISTER[SECOND_NAME]']");
2659                        if ($input.length && arFio[2]) $input.val(arFio[2]).addClass("success");
2660                        var $input = $("[name='REGISTER[PERSONAL_PHONE]']");
2661                        var val = $data.UF_PHONE;
2662                        if ($input.length && (val.trim().length)) $input.val(val).addClass("success");
2663                        var $input = $("[name='REGISTER[EMAIL]']");
2664                        var val = $data.UF_EMAIL;
2665                        if ($input.length && (val.trim().length)) $input.val(val).addClass("success");
2666                    }
2667                } else {
2668                    $form.replaceWith($(data).find("form"));
2669                    obPlaceHolder.bind();
2670                    if ($(data).find(".success").length) {
2671                        var $link = $("[data-has-card]");
2672                        var $cardNumber = $(data).find("[data-card-number]");
2673                        if ($link.length) $link.replaceWith("Номер карты: " + $cardNumber.html());
2674                    }
2675                }
2676
2677            }
2678        });
2679        return false;
2680    },
2681
2682    getConfirmCode: function (self) {
2683        var $self = $(self);
2684        var $form = $self.parents("form");
2685        $form.submit();
2686    }
2687};
2688
2689var obYandexRouter = {
2690
2691
2692    currentPoint: false,
2693    id: "map",
2694    currentAdress: "",
2695    stockCoords: [55.72967, 37.398666],
2696    bounds: [
2697        [57.450128, 33.675873],
2698        [53.953954, 41.388275]
2699    ],
2700    suggest: false,
2701
2702    handAddress: function (self) {
2703        console.log("handAddress")
2704
2705        //ручной ввод адреса
2706        console.log('handAddress')
2707        //	console.log(self)
2708        // прячем кнопку ручного ввода
2709        $('.manualAddress').hide();
2710
2711        var $self = $(self);
2712
2713        // границы область предлагаемых адресов
2714        bounds = [
2715            [56.538976, 36.488166],
2716            [54.803946, 39.383063],
2717        ]
2718
2719        var $parent = $(".form_popup_box");
2720        var $input = $parent.find("[data-delivery-readonly]");
2721
2722        this.suggest = new ymaps.SuggestView($input[0], {
2723            results: 10,
2724            boundedBy: bounds,
2725            //strictBounds : true
2726        })
2727
2728        this.suggest.events.add('select', function (event) {
2729            var request = event.get('item').value;
2730            obYandexRouter.getName(request);
2731            console.log('select')
2732        });
2733
2734
2735    },
2736
2737    clear: function () {
2738        var $map = $("#" + obYandexRouter.id);
2739        var $form = $map.parents("form:first");
2740        var $mkadInput = $form.find("[data-mkad-input]");
2741        $mkadInput.val(0);
2742        var $addressInput = $form.find("[data-address-input]");
2743        $addressInput.text("");
2744    },
2745
2746//здесь то что касается построения маршрута
2747    setPoint: function (coords, bFirst) {
2748        if (obYandexRouter.currentPoint === false) {
2749            obYandexRouter.currentPoint = new ymaps.Placemark([coords[0], coords[1]], {
2750                    iconContent: "Доставить сюда",
2751                    // hintContent: addressName,
2752                    balloonContentHeader: "Адрес доставки:",
2753                    // balloonContentBody: addressName,
2754                    balloonContentFooter: "mirkrasok.ru"
2755                },
2756                {
2757                    draggable: true,
2758                    // geometry: {
2759                    //     type: "GeoPoint"
2760                    // },
2761                    balloonPanelMaxMapArea: 0,
2762                    preset: "islands#blueStretchyIcon",
2763                    // Заставляем балун открываться даже если в нем нет содержимого.
2764                    openEmptyBalloon: true
2765                }
2766            );
2767
2768
2769            obYandexRouter.currentPoint.events.add('dragend', function (e) {
2770                obYandexRouter.setPoint(obYandexRouter.currentPoint.geometry.getCoordinates());
2771                obYandexRouter.getName(false, true);
2772
2773            });
2774            myMap.geoObjects.add(obYandexRouter.currentPoint);
2775        } else {
2776            obYandexRouter.currentPoint.geometry.setCoordinates([coords[0], coords[1]]);
2777        }
2778
2779        console.log(ymaps);
2780        //if(!!obRoute) myMap.geoObjects.remove(obRoute);
2781        $("#" + obYandexRouter.id).block({message: "<div class='dPathCount'>Идет расчет маршрута.<br/>Пожалуйста, подождите</div>"});
2782        if (!bFirst) this.clear();
2783
2784        var iDistanceFor = 0;
2785        var iDistanceFrom = 0;
2786        var iDistanceMkad = 0;
2787
2788
2789        ymaps.route(
2790            [obYandexRouter.stockCoords, obYandexRouter.currentPoint.geometry.getCoordinates()],
2791            {
2792                mapStateAutoApply: true,
2793                Success: function () {
2794                    //alert(1);
2795                    console.log('route')
2796
2797                }
2798            }).then(
2799            function (res) {
2800                obRoute && obRoute.removeFromMap(myMap);
2801
2802                // Объединим в выборку все сегменты маршрута.
2803                var pathsObjects = ymaps.geoQuery(res.getPaths()),
2804                    edges = [];
2805
2806                // Переберем все сегменты и разобьем их на отрезки.
2807                pathsObjects.each(function (path) {
2808                    var coordinates = path.geometry.getCoordinates();
2809                    for (var i = 1, l = coordinates.length; i < l; i++) {
2810                        edges.push({
2811                            type: 'LineString',
2812                            coordinates: [coordinates[i], coordinates[i - 1]]
2813                        });
2814                    }
2815                });
2816
2817                // Создадим новую выборку, содержащую:
2818                // - отрезки, описываюшие маршрут;
2819                // - начальную и конечную точки;
2820                // - промежуточные точки.
2821                var routeObjects = ymaps.geoQuery(edges)
2822                    //.add(res.getWayPoints())
2823                    .add(res.getViaPoints())
2824                    .setOptions('strokeWidth', 3).addToMap(myMap);
2825
2826                // Найдем все объекты, попадающие внутрь МКАД.
2827                obRoute = routeObjects;
2828                //myMap.geoObjects.add(res);
2829
2830                var objectsInMoscow = routeObjects.searchInside(MKAD);
2831                Inner = objectsInMoscow;
2832
2833                // Найдем объекты, пересекающие МКАД.
2834
2835                var boundaryObjects = routeObjects.searchIntersect(MKAD);
2836                Intersect = boundaryObjects;
2837
2838                Outer = routeObjects.remove(objectsInMoscow).remove(boundaryObjects);
2839                // Раскрасим в разные цвета объекты внутри, снаружи и пересекающие МКАД.
2840
2841                Outer.setOptions({
2842                    strokeColor: '#FF05FF',
2843                    preset: false
2844                });
2845                boundaryObjects.setOptions({
2846                    strokeColor: '#06ff00',
2847                    preset: false
2848                });
2849                objectsInMoscow.setOptions({
2850                    strokeColor: '#ff0005',
2851                    preset: false
2852                });
2853
2854
2855                var iDistance = 0;
2856                for (i = 0; i < objectsInMoscow.getLength(); i++) {
2857                    obFirst = Inner.get(i);
2858                    if (!obFirst) break;
2859                    arFirstCoords = obFirst.geometry.getCoordinates();
2860                    iStep = ymaps.coordSystem.geo.getDistance(arFirstCoords[0], arFirstCoords[1]);
2861                    iDistance += iStep;
2862                }
2863                iDistanceFor = Math.ceil(iDistance / 1000);
2864                iDistance = 0;
2865                for (i = 0; i < Outer.getLength(); i++) {
2866                    obFirst = Outer.get(i);
2867                    if (!obFirst) break;
2868                    arFirstCoords = obFirst.geometry.getCoordinates();
2869                    iStep = ymaps.coordSystem.geo.getDistance(arFirstCoords[0], arFirstCoords[1]);
2870                    iDistance += iStep;
2871                }
2872                console.log('Outer.getLength()', Outer.getLength())
2873                iDistanceFrom = Math.ceil(iDistance / 1000);
2874
2875
2876                var $map = $("#" + obYandexRouter.id);
2877                var $form = $map.parents("form:first");
2878                var $mkadInput = $form.find("[data-mkad-input]");
2879                $mkadInput.val(iDistanceFrom);
2880                var $addressInput = $form.find("[data-address-input]");
2881                $addressInput.val(obYandexRouter.currentAdress);
2882
2883                console.log('currentAdress')
2884                console.log(obYandexRouter.currentAdress)
2885                $('#ADDRESS_INPUT').val(obYandexRouter.currentAdress);
2886                $('#mkadkm').val(iDistanceFrom);
2887                $(".adreas-area")[0].style.height = 'auto';
2888                // Устанавливаем высоту текстового поля в зависимости от его содержимого
2889                $(".adreas-area")[0].style.height = $(".adreas-area")[0].scrollHeight + 'px';
2890                $('.VALID_ADDRESS').val(1)
2891                $('.manualAddress').hide();
2892                $('.addressInput').attr('readonly', 'readonly')
2893                $(".basketn-div__col.form_popup_box ymaps").css({display:"none"})
2894
2895                // Объекты за пределами МКАД получим исключением полученных выборок из
2896                // исходной.
2897                Outer.setOptions({
2898                    strokeColor: '#0010ff',
2899                    preset: 'twirl#blueDotIcon'
2900                });
2901
2902                $("#" + obYandexRouter.id).unblock();
2903
2904                $("#x").val(obYandexRouter.currentPoint.geometry.getCoordinates()[0]);
2905                $("#y").val(obYandexRouter.currentPoint.geometry.getCoordinates()[1]);
2906
2907                //myMap.geoObjects[0].set.properties('balloonContentBody', "testtestets");
2908
2909                myMap.geoObjects.each(function (geoObj) {
2910
2911                        var cont = geoObj.properties.get('iconContent');
2912
2913                        if (cont == 'Доставить сюда') {
2914                            //         console.log(cont);
2915                            geoObj.properties.set('balloonContentBody', obYandexRouter.currentAdress);
2916                            geoObj.properties.set('hintContent', obYandexRouter.currentAdress);
2917                        }
2918                    },
2919                    this);
2920
2921                myMap.setCenter(
2922                    [coords[0], coords[1]],
2923                    14
2924                );
2925
2926                if (!bFirst) obOrder.ajaxPrice();
2927
2928
2929            });
2930
2931        //myMap.setBounds(myMap.geoObjects.getBounds());
2932    },
2933
2934    createMap: function (coords) {
2935        myMap = new ymaps.Map(obYandexRouter.id, {
2936            center: [55.753994, 37.622093],
2937            zoom: 9,
2938            controls: ['smallMapDefaultSet']
2939        }, {
2940            restrictMapArea: obYandexRouter.bounds
2941        });
2942
2943        var searchControl = myMap.controls.get('searchControl');
2944        // obYandexRouter.searchF = searchControl;
2945        // searchControl.options.set("suppressYandexSearch",false);
2946        // searchControl.options.set("noSuggestPanel",false);
2947        // searchControl.options.set("noPopup",true);
2948        // searchControl.options.set("noPlacemark",true);
2949        // searchControl.options.set("noCentering",true);
2950        // searchControl.state.set("size","large");
2951        searchControl.events.add('submit', function (e) {
2952            obYandexRouter.getName(searchControl.getRequestString());
2953            return false;
2954        }, this);
2955
2956
2957        myMap.controls.add('zoomControl', {left: '10px', top: '5px'});
2958
2959        myMap.controls.remove('trafficControl');
2960        myMap.controls.remove('typeSelector');
2961
2962        var obStorePoint = new ymaps.Placemark(obYandexRouter.stockCoords,
2963            {},
2964            {
2965                draggable: false,
2966                geometry: {
2967                    type: "GeoPoint"
2968                },
2969                iconLayout: 'default#image',
2970                iconImageHref: '/i/icons/map/mk_spot.svg',
2971                iconImageSize: [25, 32],
2972                hideIconOnBalloonOpen: false
2973            }
2974        );
2975        myMap.geoObjects.add(obStorePoint);
2976
2977
2978        let $oldCoordinates = [[
2979            [55.860823, 37.388772],
2980            [55.880706, 37.396839],
2981            [55.891512, 37.432546],
2982            [55.899421, 37.479581],
2983            [55.918898, 37.532453],
2984            [55.924103, 37.586011],
2985            [55.911427, 37.629613],
2986            [55.901736, 37.699479],
2987            [55.890161, 37.741193],
2988            [55.853631, 37.809943],
2989            [55.830594, 37.859124],
2990            [55.779632, 37.874316],
2991            [55.702559, 37.859467],
2992            [55.680257, 37.85037],
2993            [55.648819, 37.857579],
2994            [55.605307, 37.796125],
2995            [55.589075, 37.769517],
2996            [55.557271, 37.681112],
2997            [55.561747, 37.591848],
2998            [55.581394, 37.500866],
2999            [55.603947, 37.466878],
3000            [55.634839, 37.449369],
3001            [55.662406, 37.411604],
3002            [55.68627, 37.384137],
3003            [55.714964, 37.37298],
3004            [55.745769, 37.348432],
3005            [55.832044, 37.354183]
3006        ]];
3007
3008        let $newCoordinates = [[
3009            [55.897702887224796, 37.67240905761718],
3010            [55.89664192633831, 37.6752414703369],
3011            [55.89591852721012, 37.67807388305662],
3012            [55.8956291637662, 37.6829662322998],
3013            [55.89538802590739, 37.687686920166],
3014            [55.89553270880329, 37.69146347045898],
3015            [55.89529157034246, 37.69669914245605],
3016            [55.89466460330075, 37.69996070861816],
3017            [55.89312125646775, 37.705282211303704],
3018            [55.89215663339145, 37.70751380920409],
3019            [55.89152961547806, 37.70957374572752],
3020            [55.89046848506115, 37.712148666381815],
3021            [55.888635554797155, 37.715324401855455],
3022            [55.8874296322104, 37.71798515319823],
3023            [55.88622367199341, 37.720216751098604],
3024            [55.88545183770592, 37.722448348999016],
3025            [55.884872951875, 37.72493743896484],
3026            [55.884872951875, 37.73025894165038],
3027            [55.88279853978146, 37.73025894165038],
3028            [55.8811582281455, 37.73111724853514],
3029            [55.880000319199695, 37.7330913543701],
3030            [55.87903536858371, 37.735065460205064],
3031            [55.87816689243558, 37.737468719482415],
3032            [55.87464453915709, 37.743562698364244],
3033            [55.86373768471359, 37.76553535461424],
3034            [55.84804765603748, 37.79574775695799],
3035            [55.833558904954586, 37.8228702545166],
3036            [55.83148173964286, 37.82776260375975],
3037            [55.83090204571783, 37.83093833923339],
3038            [55.82925953247555, 37.831968307495096],
3039            [55.824331574788744, 37.83746147155761],
3040            [55.82186736083274, 37.83866310119629],
3041            [55.81930634494508, 37.83995056152341],
3042            [55.81640687737011, 37.84115219116209],
3043            [55.815923611680155, 37.84321212768552],
3044            [55.815198701844565, 37.84458541870117],
3045            [55.814038817900894, 37.84381294250486],
3046            [55.81244392079273, 37.84252548217771],
3047            [55.81075229152879, 37.84063720703125],
3048            [55.80698210925112, 37.84106636047361],
3049            [55.80209966167469, 37.841667175292955],
3050            [55.80011750252675, 37.84192466735837],
3051            [55.780193594328715, 37.84381294250486],
3052            [55.77913351008552, 37.844783264391616],
3053            [55.77845628577709, 37.84701486229202],
3054            [55.77792417267178, 37.84813066124222],
3055            [55.776618045932416, 37.84778733848831],
3056            [55.77526349769469, 37.84581323265335],
3057            [55.773812143546046, 37.844697433703146], [55.75997317538473, 37.84426828026078], [55.753487486017335, 37.84435411094925], [55.75198691106874, 37.8441824495723], [55.74898558725352, 37.84383912681839], [55.74675864876349, 37.845555740587926], [55.7449673229946, 37.84950395225785], [55.74482207674487, 37.85173555015823], [55.74332116703625, 37.85019059776566], [55.741481263136315, 37.844869095080114], [55.736784271297495, 37.8430666506221], [55.73179612239952, 37.84289498924515], [55.731166504711425, 37.844697433703146], [55.72898698012023, 37.84177919029495], [55.72491820726679, 37.841521698229506], [55.72080056319119, 37.84092088341019], [55.71818442163351, 37.845126587145536], [55.716585581821896, 37.84435411094925], [55.71571345967627, 37.840405899279325], [55.713823794608125, 37.84135003685256], [55.7119340377362, 37.84461160301467], [55.710722606838814, 37.84461160301467], [55.709414219096786, 37.84169335960648], [55.70985035323334, 37.83731599449416], [55.70849347541899, 37.83851762413284], [55.70645806996491, 37.83971925377152], [55.70587650599171, 37.83774514793656], [55.705149538801436, 37.83551355003615], [55.70350169621928, 37.8343119203975], [55.701708376470975, 37.833110290758825], [55.69758827484921, 37.83216615318557], [55.69356469588598, 37.83156533836623], [55.6894922165988, 37.832766968004904], [55.686631530014225, 37.83499856590531], [55.684207054812255, 37.83748765587111], [55.6821703789833, 37.83499856590531], [55.680279084622, 37.834655243151396], [55.678775682559596, 37.83620019554396], [55.675235183954115, 37.83723016380569], [55.667182989135455, 37.840405899279325], [55.66053624948339, 37.84203668236037], [55.65641179002368, 37.84263749717971], [55.6535972024768, 37.84014840721388], [55.64859838232795, 37.83448358177445], [55.64529783914648, 37.83027787803908], [55.64243390621512, 37.82572885154982], [55.63913284127208, 37.824613052599645], [55.637919144215985, 37.818604904406286], [55.62854813179519, 37.80358453392288], [55.61820341705874, 37.78667588829299], [55.617086218110366, 37.78899331688187], [55.614948878859664, 37.78959413170121], [55.61509461025296, 37.7873625338008], [55.614997456051206, 37.784444290392614], [55.614997456051206, 37.78075357078811], [55.61120825360195, 37.773543792956076], [55.60217097907149, 37.75852342247268], [55.59726276567736, 37.74642129539749], [55.59342323822858, 37.736464935534215], [55.59118739019748, 37.733718353502965], [55.58875697549044, 37.73251672386429], [55.58875697549044, 37.72891183494826], [55.5889514142296, 37.72530694603226], [55.58584027831145, 37.71826882957717], [55.58345814747422, 37.7134623110225], [55.58127034840715, 37.7057375490596], [55.57845033787414, 37.69964357017777], [55.577088880670665, 37.695094543688505], [55.575532871526356, 37.692691284411154], [55.57358777301203, 37.692262130968786], [55.57120489546283, 37.69234796165726], [55.57188573243677, 37.689773041002965], [55.57266381732086, 37.68642564415238], [55.572128885626164, 37.68239160179398], [55.57057267908735, 37.67071862816117], [55.57042678154921, 37.655612426989286], [55.57086447253071, 37.645570236437536], [55.571496684188844, 37.63930459617874], [55.57208025510925, 37.63381143211625], [55.57208025510925, 37.62437005638381], [55.57266381732086, 37.621108490221694], [55.57353914430943, 37.61527200340529], [55.57383091561797, 37.61115213035842], [55.573879543957716, 37.606860595934606], [55.573101483264445, 37.603684860460966], [55.57144805288571, 37.60196824669143], [55.56896777623045, 37.60308404564163], [55.56648734226576, 37.601624923937536], [55.5659036878825, 37.59759088157914], [55.56673052902162, 37.59467263817092], [55.57008635184344, 37.593642669909215], [55.57378228721773, 37.59252687095901
3057], [55.57601913103611, 37.58969445823929], [55.57699163191336, 37.5841154634883], [55.57854758300307, 37.577163177721715], [55.579617263456626, 37.5727858126094], [55.58039519449406, 37.569524246447294], [55.58195101012762, 37.56188531517287], [55.58972915951208, 37.530900436632834], [55.58919446129312, 37.52729554771683], [55.590652711931135, 37.52592225670121], [55.592256724782665, 37.52223153709671], [55.59313161313196, 37.5185408174922], [55.59415229144777, 37.51373429893752], [55.59677677040253, 37.50738282799025], [55.599012298609146, 37.50369210838577], [55.60192801271931, 37.49931474327346], [55.604843509200315, 37.49776979088089], [55.60722433656079, 37.494594055407255], [55.6090220079864, 37.491332489245146], [55.60790454629169, 37.48910089134476], [55.60596105848462, 37.48747010826369], [55.611256835447605, 37.488585907213896], [55.61412305735588, 37.48686929344436], [55.61834913630358, 37.48111863731642], [55.62340040051834, 37.47622628807327], [55.62786828167662, 37.47099061607619], [55.632044316744654, 37.46661325096388], [55.63592859929264, 37.46172090172073], [55.63665685921782, 37.458373504870146], [55.63626845561624, 37.45622773765824], [55.63578294567616, 37.45348115562697], [55.63811333828267, 37.455111938708036], [55.64068631839994, 37.455541092150426], [55.64660838237857, 37.44910379051468], [55.6556353723766, 37.43837495445512], [55.65903208541546, 37.43416925071975], [55.659905478070506, 37.431079345934585], [55.66063329033317, 37.42884774803421], [55.660875891400586, 37.426616150133825], [55.66330181902196, 37.429105240099624], [55.66655232529556, 37.427817779772475], [55.680279084622, 37.4175180971553], [55.688910399066174, 37.41305490135452], [55.69293445909798, 37.407990890734396], [55.698994005599275, 37.40052362083694], [55.70049662715336, 37.39691873192091], [55.702726216740054, 37.39503045677445], [55.705343398046864, 37.393142181627965], [55.70626421627299, 37.39176889061234], [55.70960805709442, 37.3874773561885], [55.71144946990421, 37.38567491173048], [55.71237014362427, 37.382413345568374], [55.712757789198164, 37.38078256248733], [55.714938223574464, 37.3838724672725], [55.718620457447926, 37.38224168419143], [55.72307743204297, 37.38009591697952], [55.72661358103612, 37.378207641833036], [55.72985880462025, 37.37657685875199], [55.72981037043872, 37.37219949363968], [55.72951976408239, 37.36653466820022], [55.73005254074289, 37.3611273348262], [55.731892985754094, 37.37134118675492], [55.734992485659596, 37.373057800524435], [55.74501573829052, 37.368680435412145], [55.751212398090566, 37.36773629783889], [55.76215096246012, 37.36799378990431], [55.76418345353268, 37.36550469993851], [55.76655455864643, 37.36610551475785], [55.76849004730127, 37.368251281969755], [55.77158662843581, 37.36567636131546], [55.77361862555876, 37.36893792747757], [55.77739205226982, 37.36893792747757], [55.7812134822765, 37.36885209678909], [55.78493780505847, 37.369023758166044], [55.787404367494126, 37.37031121849319], [55.78943553645033, 37.36885209678909], [55.791369884195, 37.36430307029983], [55.792530446538024, 37.374259430163114], [55.79562510967724, 37.377520996325224], [55.80031498774618, 37.381898361437536], [55.80442420841985, 37.38533158897659], [55.808484657453775, 37.387563186876974], [55.82303110743136, 37.39185472130082], [55.83076121703942, 37.39417214988967], [55.831727372273825, 37.39099641441603], [55.83192060042838, 37.388421493761754], [55.831775679402845, 37.38558908104201], [55.83414265491183, 37.38576074241899], [55.83568835674609, 37.38782067894242], [55.834625693362945, 37.392369705431676], [55.835640054497695, 37.39554544090529], [55.839648936077, 37.39468713402053], [55.84394715517475, 37.391940551989286], [55.84814832383642, 37.39133973716995], [55.85452164003844, 37.39460130333206], [55.85959057388015, 37.39674707054397], [55.86311429845631, 37.399665313952184], [55.866782492613076, 37.40378518699905], [55.86924384891148, 37.407733398668974], [55.8718980772097, 37.41219659446976], [55.873876565242476, 37.418204742663114], [55.875565438348396, 37.4226679384639], [55.87947369034666, 37.43477006553909], [55.88121056442022, 37.44077821373244], [55.884442872291174, 37.4417223513057], [55.88285087383534, 37.4453272402217], [55.88285087383534, 37.44970460533402], [55.882995603677216, 37.458287674181676], [55.883815729211854, 37.46661325096388], [55.885745367711415, 37.47339387535355], [55.888784352998634, 37.48257775902054], [55.889122003279596, 37.48549600242873], [55.889218474246576, 37.488500076525426], [55.89119607599798, 37.492619949572294], [55.89433109088146, 37.49450822471878], [55.894041715548205, 37.50043054222366], [55.90055213634929, 37.51373429893752], [55.90416856273664, 37.52214570640823], [55.9071096731802, 37.532445389025426], [55.90826676999187, 37.54059930443069], [55.91115936034281, 37.54471917747756], [55.90870067235796, 37.5464357912471], [55.91038802410236, 37.56274362205765], [55.91130398417253, 37.57338662742874], [55.91140039975807, 37.58248468040726], [55.91072548560348, 37.58737702965042], [55.91279839869436, 37.59055276512405], [55.90870067235796, 37.594071823351584], [55.90720609923871, 37.6005949556758], [55.90508467033431, 37.60797639488478], [55.90064857878059, 37.626687484972685], [55.89789987512875, 37.64428277611039], [55.89621197772044, 37.65990396141311], [55.89577793503864, 37.668057876818395], [55.897702887224796, 37.67240905761718]]];
3058
3059        var myGeometry = {
3060            type: 'Polygon',
3061            coordinates: $newCoordinates
3062        };
3063
3064        MKAD = new ymaps.GeoObject(
3065            {
3066                geometry: myGeometry,
3067                properties: {
3068                    balloonContent: false
3069                }
3070            },
3071            {
3072                fill: false,
3073                //fillColor: '#332987',
3074                opacity: 0.3,
3075                zIndex: 401,
3076                strokeWidth: 0,
3077
3078                interactivityModel: 'default#transparent'
3079            }
3080        );
3081        myMap.geoObjects.add(MKAD);
3082        myMap.setBounds(myMap.geoObjects.getBounds());
3083
3084        myMap.events.add('click', function (e) {
3085            var coords = e.get('coords');
3086
3087            obYandexRouter.setPoint(coords);
3088            obYandexRouter.getName(false, true);
3089        });
3090        if (coords.length) {
3091            bFirst = true;
3092            obYandexRouter.setPoint(coords, true);
3093        }
3094
3095
3096        obYandexRouter.handAddress();
3097
3098    },
3099    saveManual: function () {
3100        sSearch = $('[name="ADDRESS[ADDRESS]"]').val();
3101        $('')
3102        obYandexRouter.getName(sSearch);
3103    },
3104
3105    getName: function (sAdressName, bNosetPoint) {
3106        console.log('YR getName')
3107
3108        if (!sAdressName) {
3109            sAdressName = obYandexRouter.currentPoint.geometry.getCoordinates();
3110        }
3111        var options = {
3112            kind: 'house'
3113        };
3114        if (!$.isArray(sAdressName)) {
3115            options.strictBounds = true;
3116            options.boundedBy = obYandexRouter.bounds;
3117            options.results = 10;
3118
3119        }
3120        var geo = ymaps.geocode(sAdressName, options);
3121
3122        console.log('YR sAdressName')
3123        console.log(sAdressName)
3124
3125
3126        geo.then(
3127            function (res) {
3128                var first = res.geoObjects.get(0);
3129
3130                console.log('first')
3131                console.log(first)
3132//						console.log('sAdressName')
3133//						console.log(typeof(sAdressName))
3134//						console.log(sAdressName)
3135//						console.log('res')
3136//						console.log(res)
3137                console.log(bNosetPoint)
3138
3139                if (first) {
3140                    console.log('select?')
3141                    var cityName = first.properties.get('metaDataProperty.GeocoderMetaData.AddressDetail
3141s.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName');
3142                    var address = first.properties.getAll();
3143                    obYandexRouter.currentAdress = (!!address.text) ? address.text : "";
3144
3145                    if (!bNosetPoint) obYandexRouter.setPoint(first.geometry.getCoordinates());
3146
3147                } else {
3148                    if ($.isArray(sAdressName)) {
3149                        obYandexRouter.currentAdress = "GPS координаты: " + sAdressName[0] + ", " + sAdressName[1];
3150                    } else {
3151                        regexp = /\d{1,2}\.\d{1,20}\,\s?\d{1,2}\.\d{1,20}/;
3152                        console.log('test RE')
3153                        console.log('sAdressName')
3154                        console.log(sAdressName)
3155                        console.log(regexp.test(sAdressName))
3156
3157                        //55.63027376527422, 37.556289724918216
3158                        if (regexp.test(sAdressName)) {
3159                            sAdressName = sAdressName.replace(/[a-zA-Zа-яА-Я]*/gm, '')
3160                            sAdressName = sAdressName.replace(/[а-яА-Я]*/gm, '')
3161                            sAdressName = sAdressName.replace(/\s*/gm, '')
3162                            sAdressName = sAdressName.replace(/\:*/gm, '')
3163                            coords = sAdressName.split(",");
3164                            console.log(coords)
3165                            obYandexRouter.setPoint(coords)
3166                        } else {
3167                            alert("Заданный адрес не найден либо не относится к Москве или Московской области");
3168                            $('.VALID_ADDRESS').val(0)
3169                            $('.addressInput').val("")
3170
3171                        }
3172                    }
3173                }
3174            }
3175        );
3176    },
3177
3178    startAddress: function (obj, bNoWait) {
3179        //this.clear();
3180        var $input = $(obj);
3181        $input.stopTime();
3182        var sSearch = $input.val();
3183        if (!sSearch.length) return;
3184        if (bNoWait) {
3185            obYandexRouter.getName(sSearch);
3186            return false;
3187        }
3188        $input.stopTime();
3189        $input.oneTime(1000, function () {
3190            obYandexRouter.getName(sSearch);
3191        });
3192    },
3193
3194    searchInput: function (self, e) {
3195        var $self = $(self);
3196        if (e.keyCode == 13) {
3197
3198            $self.next().trigger("click");
3199            return false;
3200        }
3201        /* $self.stopTime();
3202         if($(self).val().length)
3203         {
3204         /!*$self.oneTime("5s",function(){
3205         obYandexRouter.startAddress(self, true);
3206         });*!/
3207         }*/
3208
3209    }
3210};
3211
3212var obRobotint = {
3213
3214    prices: [],
3215
3216    processPrice: function ($priceObj, data) {
3217
3218        if (window.rt_debug) {
3219            console.log('$priceObj, data')
3220            console.log($priceObj.data())
3221            console.log(data)
3222        }
3223        // че за цена?
3224        // берем цену с кнопки "выбрать цвет"
3225        // по какой то причне в массиве data не передается при первом клике данные
3226        var price = FloatVal($priceObj.data("price-per-can"));
3227
3228        var RT_Volume = FloatVal($priceObj.data("priceRef_can_volume"))
3229
3230        // на кой приравниваем к  цене магазина до приведения к группировочной цене
3231        var shopPrice = price;
3232
3233        // объем колеруемого продукта
3234        // если у нас не указан объем  то берем объем из RT
3235        if (!data.VOLUME) {
3236            var iVolume = RT_Volume;
3237        } else {
3238            var iVolume = FloatVal(data.VOLUME);
3239        }
3240        if (!iVolume) iVolume = 1;
3241
3242        if (window.rt_debug) {
3243            console.log('PPC')
3244            console.log(price)
3245            console.log('PPL')
3246            console.log(FloatVal($priceObj.data("pricePerLitr")))
3247            console.log("priceRef_can_volume")
3248            console.log(FloatVal($priceObj.data("priceRef_can_volume")))
3249            console.log("data.VOLUME")
3250            console.log(data.VOLUME)
3251            console.log("iVolume")
3252            console.log(iVolume)
3253
3254        }
3255
3256
3257        if (window.rt_debug) {
3258            console.log(iVolume)
3259        }
3260
3261        // обратное действие от делим стоимость банки на колеруемый объем получаем PPL
3262        var division = shopPrice / iVolume;
3263
3264        if (window.rt_debug) {
3265            console.log(division)
3266        }
3267        // ID системы колеровки
3268        var COLLECTION_VENDOR_ID = data.COLLECTION_VENDOR_ID
3269//console.log('COLLECTION_VENDOR_ID')
3270//console.log(COLLECTION_VENDOR_ID)
3271
3272        // обходим цены из ИБ Клеровка Роботинт для того что бы выбрать нужный продукт в
3273        // в соответствующем ценовом диапазоне и соответствующей системы
3274
3275
3276        console.log('robotint', obRobotint.prices)
3277        for (var i in obRobotint.prices) {
3278            // ID системы колеровки
3279
3280
3281
3282            TINT_SYSTEM_ID = obRobotint.prices[i].TINT_SYSTEM_ID
3283            // товары для добавления в корзину с ценовыми уровнями
3284            var priceBlock = obRobotint.prices[i];
3285
3286            // отбираем только в нужной системе
3287
3288            console.log('COLLECTION_VENDOR_ID', COLLECTION_VENDOR_ID)
3289            console.log('TINT_SYSTEM_ID', TINT_SYSTEM_ID)
3290            if( COLLECTION_VENDOR_ID == 18){COLLECTION_VENDOR_ID = 3;}
3291            if( COLLECTION_VENDOR_ID == 19){COLLECTION_VENDOR_ID = 3;}
3292            if( COLLECTION_VENDOR_ID == 100){COLLECTION_VENDOR_ID = 5;}
3293            if( COLLECTION_VENDOR_ID == 103){COLLECTION_VENDOR_ID = 3;}
3294
3295            if (COLLECTION_VENDOR_ID == TINT_SYSTEM_ID) {
3296                console.log('obRobotint.prices', priceBlock)
3297                // ищем соответствующий ценовой диапазон
3298                if ((division > FloatVal(priceBlock.FROM)) && (division <= FloatVal(priceBlock.TO))) {
3299                    if (window.rt_debug) {
3300                        console.log("Выбран товар")
3301                        console.log(priceBlock)
3302                    }
3303                    // если в выбраном товаре приведенная цена  = 0, значит берем актуальную с тем округлением каким нам надо
3304                    if (parseInt(priceBlock.PRICE) == 0 || priceBlock.PRICE == '') {
3305                        // например округление до 10 рублей вверх
3306                        shopPrice = Math.ceil(price / 100) * 100;
3307                        if (window.rt_debug) console.log('shopPrice ', shopPrice)
3308                    } else {
3309                        shopPrice = FloatVal(priceBlock.TO) * iVolume;
3310                    }
3311                    obColorer.productData.COLOR_SKU_ID = priceBlock.SKU_ID;
3312                    break;
3313                }
3314            }
3315        }
3316
3317        console.log('obrobotint', obColorer.productData.COLOR_SKU_ID)
3318        if (window.rt_debug) {
3319            console.log('COLOR_SKU_ID')
3320            console.log(obColorer.productData.COLOR_SKU_ID)
3321            console.log('shopPrice')
3322            console.log(shopPrice)
3323        }
3324
3325        if (shopPrice != price) {
3326            // переписываем значение кнопки на клиентские, приведенные к нужному уровню
3327            $priceObj.attr("data-price-shop", shopPrice);
3328            $priceObj.text(number_format(shopPrice, 0, ".", " ") + " ₽");
3329        }
3330    },
3331
3332    select: function (data) {
3333
3334        if (window.rt_debug) {
3335            console.log(data)
3336        }
3337        var iProductID = parseInt(data.PRODUCT_ID);
3338        var $itemObject = obColorer.itemObject;
3339        if (iProductID) {
3340            var action = "add";
3341            var bBigBasket = $("[data-big-basket]").length;
3342
3343            var iBasketID = data.BASKET_ID;
3344
3345            var $basketItem = [];
3346            if (iBasketID) {
3347                action = "colorate-change";
3348                obColorer.close();
3349                $basketItem = $("[data-basket-colorate='" + data.BASKET_ID + "']");
3350            }
3351
3352            if (bBigBasket) {
3353                data.BIG_BASKET = 1;
3354            } else if ($("[data-big-basket-new]").length) {
3355                data.BIG_BASKET = 1;
3356                data.COLORATE_USE = "Y";
3357                data.basket_new = "Y";
3358            }
3359
3360            data.action = action;
3361            $.ajax({
3362                type: "POST",
3363                url: "/local/components/art-fresh/sale.basket/ajax.php",
3364                data: data,
3365                timeout: 15000,
3366                beforeSend: function () {
3367                    if (window.rt_debug) console.log(data)
3368                    if ($basketItem && $basketItem.length) {
3369                        $basketItem.addClass("loading");
3370                    }
3371                },
3372                success: function (data, textstatus) {
3373                    if ($basketItem && $basketItem.length) {
3374                        $basketItem.removeClass("loading");
3375                    }
3376                    obProduct.productAdded(iProductID, true);
3377                    obBasket.changeBasket(data);
3378                    if (typeof obBigBasket !== 'undefined') {
3379                        obBigBasket.changeBasket(data);
3380                    }
3381
3382                },
3383                error: function () {
3384                    if ($basketItem && $basketItem.length) {
3385                        $basketItem.removeClass("loading");
3386                    }
3387                }
3388            });
3389        }
3390    }
3391};
3392
3393var obComparsion = {
3394
3395    get: function (iSKUID) {
3396        $.fancybox({
3397            type: "ajax",
3398            width: 800,
3399            href: "/local/components/art-fresh/catalog.sku.prices/ajax.php?ID=" + iSKUID,
3400            helpers: {
3401                overlay: {
3402                    locked: false
3403                }
3404            },
3405            afterShow: function () {
3406                obComparsion.processPrice();
3407            }
3408        });
3409    },
3410
3411    getCurrentRRCPrice: function () {
3412        var $parent = $("[data-comparsion-parent]");
3413        var totalRRC = FloatVal($parent.find("[data-basket-rrc]").attr("data-basket-rrc"));
3414        var $rrc = $parent.find("td[data-rrc-price]");
3415        var quantity = $parent.find("[data-quantity]").val();
3416        totalRRC += FloatVal($rrc.attr("data-rrc-price")) * quantity;
3417        return totalRRC;
3418    },
3419
3420    processPrice: function () {
3421        var $parent = $("[data-comparsion-parent]");
3422        var rrcPrice = this.getCurrentRRCPrice();
3423        var $items = $parent.find("[data-price-line]");
3424        var curPriceType = "rrc";
3425        $items.each(function () {
3426            var iPrice = $(this).attr("data-price-line");
3427            if (rrcPrice > iPrice) {
3428                curPriceType = $(this).attr("data-code");
3429            }
3430        });
3431        var $priceItems = $parent.find("[data-mk-price]");
3432        var $priceItem = $priceItems.removeClass("selected").filter("[data-" + curPriceType + "-price]").addClass("selected");
3433
3434        var mkPrice = FloatVal($priceItem.attr("data-" + curPriceType + "-price"));
3435
3436        var vendor = {
3437            price: mkPrice,
3438            vendor_name: "",
3439            price_formatted: $priceItem.html()
3440        };
3441
3442        $parent.find("[data-vendor-price]").each(function () {
3443            var $this = $(this);
3444            var curPrice = FloatVal($this.data("vendor-price"));
3445            if (!curPrice) return;
3446            if (curPrice < vendor.price) {
3447                vendor.price = curPrice;
3448                vendor.price_formatted = $this.html();
3449                vendor.vendor_name = $this.data("vendor-name");
3450            }
3451        });
3452
3453        var $buyPrice = $parent.find("[data-buy-price]");
3454        $buyPrice.html(vendor.price_formatted);
3455        var $buyButton = $parent.find("[data-buy-button]");
3456        $buyButton.attr({"data-vendor": vendor.vendor_name});
3457    },
3458
3459    changeQuantity: function (self, sTurn, bRefresh) {
3460        'use strict';
3461        var $obParent = $(self).parents("[data-quantity-parent]:first");
3462        var $obQuantity = $obParent.find("[data-quantity]");
3463        var iQuantity = IntVal($obQuantity.val());
3464        var $obProduct = $(self).parents("[data-comparsion-parent]:first");
3465        var obParentData = $obProduct.data();
3466        var iProductID = obParentData.productId;
3467        var iMinValue = ($obQuantity.hasAttr("data-min-value")) ? IntVal($obQuantity.attr("data-min-value")) : 1;
3468        if (!!sTurn) {
3469            switch (sTurn) {
3470                case "plus":
3471                    iQuantity++;
3472                    break;
3473                case "minus":
3474                    if (iQuantity > iMinValue) iQuantity--;
3475                    break;
3476            }
3477        } else {
3478            iQuantity = IntVal(iQuantity);
3479        }
3480        if (iQuantity < 0) return;
3481        $obQuantity.val(iQuantity).attr("data-changed", 1);
3482        this.processPrice();
3483        return false;
3484    },
3485
3486
3487    bind: function () {
3488        var $parent = $("[data-comparsion-parent]");
3489        if ($parent.length) {
3490            obComparsion.processPrice();
3491        }
3492    }
3493};
3494
3495var obFastOrder = {
3496    afterShow:function () {
3497
3498        $('.typePhone').mask("+9 (999) 999-99-99");
3499        obFastOrder.bind();
3500
3501        document.addEventListener("paste", function (e) {
3502            var pastedText = undefined;
3503            if (window.clipboardData && window.clipboardData.getData) {
3504                pastedText = window.clipboardData.getData('Text');
3505            } else if (e.clipboardData && e.clipboardData.getData) {
3506                pastedText = e.clipboardData.getData('text/plain');
3507            }
3508
3509            if ($(e.target).hasClass('typePhone')) {
3510                var v = pastedText,
3511                    v2 = v.replace(/\D/g, ""),
3512                    letters = v2.split('');
3513
3514                if (v2.length == 11) {
3515                    if (letters[0] == 7 || letters[0] == 8) {
3516                        delete letters[0];
3517                        $(e.target).mask("+7 (999) 999-99-99");
3518                        $(e.target).val(letters.join(''))
3519                    }
3520                } else if (v2.length > 11) {
3521                    if (letters[0] == '+' && letters[1] == 7) {
3522                        delete letters[1];
3523                        delete letters[0];
3524                        $(e.target).mask("+7 (999) 999-99-99");
3525                        $(e.target).val(letters.join(''))
3526                    }
3527                } else {
3528                    $(e.target).mask("+7 (999) 999-99-99");
3529                    $(e.target).val(letters.join(''))
3530                }
3531            }
3532            return false;
3533        });
3534    },
3535    getDolymi: function (iSKUID) {
3536        $.fancybox({
3537            type: "ajax",
3538            href: "/local/components/art-fresh/fast.order/ajax.php?FAST_ORDER[PaySystem]=24&FAST_ORDER[SKU_ID]=" + iSKUID,
3539
3540            afterShow:this.afterShow,
3541            helpers: {
3542                overlay: {
3543                    locked: false
3544                }
3545            }
3546        });
3547    },
3548    get: function (iSKUID) {
3549        $.fancybox({
3550            type: "ajax",
3551            href: "/local/components/art-fresh/fast.order/ajax.php?FAST_ORDER[SKU_ID]=" + iSKUID,
3552            afterShow:this.afterShow,
3553            helpers: {
3554                overlay: {
3555                    locked: false
3556                }
3557            }
3558        });
3559    },
3560
3561    submit: function (self) {
3562        'use strict';
3563        var $form = $(self);
3564
3565        var obData1 = new FormData(self);
3566        if (!$form.hasClass("loading")) {
3567
3568            $form.validate({
3569                rules: {
3570                    "FAST_ORDER[PHONE]": {
3571                        phone: 10
3572                    }
3573                }
3574            });
3575            if ($form.valid()) {
3576                var $sess = $("<input type='hidden' name='sessid' value='" + BX.bitrix_sessid() + "'/>");
3577                $sess.appendTo($form);
3578                var obData = new FormData(self);
3579
3580                $.ajax({
3581                    url: $form.attr("action"),
3582                    data: obData,
3583                    processData: false,
3584                    contentType: false,
3585                    type: "post",
3586                    timeout: 30000,
3587                    beforeSend: function () {
3588                        $form.addClass("loading");
3589                    },
3590
3591                    success: function (data) {
3592                        console.log(data);
3593                        var $replace = $(data).find("[data-fast-order] form");
3594                        $form.replaceWith($replace);
3595                        obFastOrder.bind();
3596                        ym(7500958,'reachGoal','oneclick');
3597                        //										console.log('reachGoal - oneclick')
3598                    }
3599                });
3600            }
3601        }
3602        return false;
3603    },
3604
3605    bind: function () {
3606        obPlaceHolder.bind();
3607    },
3608
3609    init: (function () {
3610        $(function () {
3611            obFastOrder.bind();
3612        });
3613    })()
3614}
3615
3616var obFastRezerv = {
3617
3618    get: function (iSKUID, store, qnt) {
3619        var params = {
3620            'REZERV[SKU_ID]': iSKUID,
3621            'REZERV[QUANTITY]': qnt,
3622            'REZERV[STORE_NAME]': store
3623        };
3624        var str = jQuery.param(params);
3625
3626        $.fancybox({
3627            type: "ajax",
3628            href: "/local/components/art-fresh/reservation.order/ajax.php?" + str,
3629            afterShow: function () {
3630                $('.typePhone').mask("+9 (999) 999-99-99");
3631                obFastOrder.bind();
3632
3633                document.addEventListener("paste", function (e) {
3634                    var pastedText = undefined;
3635                    if (window.clipboardData && window.clipboardData.getData) {
3636                        pastedText = window.clipboardData.getData('Text');
3637                    } else if (e.clipboardData && e.clipboardData.getData) {
3638                        pastedText = e.clipboardData.getData('text/plain');
3639                    }
3640
3641                    if ($(e.target).hasClass('typePhone')) {
3642                        var v = pastedText,
3643                            v2 = v.replace(/\D/g, ""),
3644                            letters = v2.split('');
3645
3646                        if (v2.length == 11) {
3647                            if (letters[0] == 7 || letters[0] == 8) {
3648                                delete letters[0];
3649                                $(e.target).mask("+7 (999) 999-99-99");
3650                                $(e.target).val(letters.join(''))
3651                            }
3652                        } else if (v2.length > 11) {
3653                            if (letters[0] == '+' && letters[1] == 7) {
3654                                delete letters[1];
3655                                delete letters[0];
3656                                $(e.target).mask("+7 (999) 999-99-99");
3657                                $(e.target).val(letters.join(''))
3658                            }
3659                        } else {
3660                            $(e.target).mask("+7 (999) 999-99-99");
3661                            $(e.target).val(letters.join(''))
3662                        }
3663                    }
3664                    return false;
3665                });
3666            },
3667            helpers: {
3668                overlay: {
3669                    locked: false
3670                }
3671            }
3672        });
3673    },
3674
3675    submit: function (self) {
3676        'use strict';
3677        var $form = $(self);
3678        if (!$form.hasClass("loading")) {
3679
3680            $form.validate({
3681                rules: {
3682                    "FAST_ORDER[PHONE]": {
3683                        phone: 10
3684                    }
3685                }
3686            });
3687            if ($form.valid()) {
3688                var $sess = $("<input type='hidden' name='sessid' value='" + BX.bitrix_sessid() + "'/>");
3689                $sess.appendTo($form);
3690                
3691                var obData = new FormData(self);
3692
3693                $.ajax({
3694                    url: $form.attr("action"),
3695                    data: obData,
3696                    processData: false,
3697                    contentType: false,
3698                    type: "post",
3699                    timeout: 30000,
3700                    beforeSend: function () {
3701                        $form.addClass("loading");
3702                    },
3703
3704                    success: function (data) {
3705                        var $replace = $(data).find("[data-fast-order] form");
3706						var isSuccess = $replace.find(".dMessage.success").length > 0;
3707                        $form.replaceWith($replace);
3708                        obFastRezerv.bind();
3709
3710                        if (isSuccess && typeof window.ym != "undefined") {
3711                            ym(7500958, "reachGoal", "form_reserv");
3712                        }
3713
3714                        //ga('send', 'event', 'callback',target);
3715                    }
3716                });
3717            }
3718        }
3719        return false;
3720    },
3721
3722    bind: function () {
3723        obPlaceHolder.bind();
3724    },
3725
3726    init: (function () {
3727        $(function () {
3728            obFastRezerv.bind();
3729        });
3730    })()
3731}
3732
3733var obInitPopup = {
3734    getAjaxTemplate: function (event, self) {
3735        'use strict';
3736        event.preventDefault();
3737        var $self = $(self);
3738        var width = 400;
3739        var height = 400;
3740        var $formFancybox;
3741
3742        $formFancybox = $.fancybox({
3743            width: width,
3744            height: height,
3745            autoWidth: false,
3746            href: $self.attr("href"),
3747            type: 'ajax',
3748            afterShow: function (instance, current) {
3749                obPlaceHolder.destroy();
3750                obPlaceHolder.bind();
3751                //$('.fancybox-inner .dTypo').typo({});
3752                //$('.fancybox-inner .dTypo').typo({});
3753            }
3754        });
3755    },
3756    onSubmit: function (event, self) {
3757        event.preventDefault();
3758        var $form = $(self);
3759        if (!$form.hasClass("loading")) {
3760            var $target = $form.find("[data-clb-target]");
3761            var target = "callback_origin";
3762            if ($target.length) {
3763                target = $target.val();
3764            }
3765
3766            var $ingateCB = $form.find("[data-ingate-target]");
3767            var ingateTarget = "zvonok";
3768            if ($ingateCB.length) {
3769                ingateTarget = $ingateCB.val();
3770            }
3771            var $parent = $form.parents(".dCallback");
3772            $form.validate({
3773                rules: {
3774                    "CALLBACK[PHONE]": {
3775                        phone: 10
3776                    }
3777                }
3778            });
3779            if ($form.valid()) {
3780                var $sess = $("<input type='hidden' name='sessid' value='" + BX.bitrix_sessid() + "'/>");
3781                $sess.appendTo($form);
3782                var obData = new FormData(self);
3783
3784                //return false;
3785                //obData.append("sessid",BX.bitrix_sessid());
3786                $.ajax({
3787                    url: $form.attr("action"),
3788                    data: obData,
3789                    processData: false,
3790                    contentType: false,
3791                    type: "post",
3792                    timeout: 30000,
3793                    beforeSend: function () {
3794                        $form.addClass("loading");
3795                    },
3796
3797                    success: function (data) {
3798
3799                        $form.replaceWith(data);
3800
3801
3802                        //ga('send', 'event', 'callback',target);
3803                    }
3804                });
3805            }
3806        }
3807    }
3808
3809}
3810
3811var obPopUpTS = {
3812    show: function (self) {
3813        'use strict';
3814
3815        var $self = $(self);
3816
3817        $.fancybox({
3818            width: 600,
3819            content: $($self).find("[data-mf-contacts]"),
3820            afterShow: function () {
3821                //obProfile.bind();
3822                ym(7500958, 'reachGoal', 'tech_spec_contacts');
3823
3824            },
3825            helpers: {
3826                overlay: {
3827                    locked: false
3828                }
3829            }
3830        });
3831
3832
3833    },
3834
3835    submit: function (self) {
3836        'use strict';
3837        var $form = $(self);
3838
3839
3840    },
3841
3842    bind: function () {
3843        obPlaceHolder.bind();
3844    },
3845
3846    init: (function () {
3847        $(function () {
3848            obPopUpTS.bind();
3849        });
3850    })()
3851}
3852
3853$(document).on('click', '.reviewsList__item__right__useful__OK', function () {
3854    var $this = $(this);
3855    $.post('/catalog/reviews_userful_add.php', {rewid: $(this).data('rewid'), func: 'ok'}, function (data) {
3856        $this.text(data.replace('int(0)', '')).css('pointer-events', 'none').next('.reviewsList__item__right__useful__noOK').css('pointer-events', 'none');
3857        BX.setCookie('userful_' + $this.data('rewid'), 'Y', {expires: 86400 * 30});
3858    });
3859});
3860$(document).on('click', '.reviewsList__item__right__useful__noOK', function () {
3861    var $this = $(this);
3862    $.post('/catalog/reviews_userful_add.php', {rewid: $(this).data('rewid'), func: 'nook'}, function (data) {
3863        $this.text(data.replace('int(0)', '')).css('pointer-events', 'none').prev('.reviewsList__item__right__useful__OK').css('pointer-events', 'none');
3864        BX.setCookie('userful_' + $this.data('rewid'), 'Y', {expires: 86400 * 30});
3865    });
3866});
3867$(document).on('click', '.reviewsListSort__item', function () {
3868    $('.reviewsListSortList').slideToggle();
3869});
3870$(document).on('click', '.reviewsListSortList__item', function () {
3871    const url = new URL(window.location);
3872    url.searchParams.set('SORT', $(this).data('sort'));
3873    url.searchParams.set('ORDER', $(this).data('order'));
3874    window.location.href = url;
3875});
3876$(document).on('click', '.reviewsList__ocenkaValue__item__checkbox__item', function () {
3877    if ($(this).is(':checked')) {
3878        const url = new URL(window.location);
3879        url.searchParams.set('OCENKA_' + $(this).val(), 'Y');
3880        window.location.href = url;
3881    } else {
3882        const url = new URL(window.location);
3883        url.searchParams.delete('OCENKA_' + $(this).val());
3884        window.location.href = url;
3885    }
3886});
3887
3888
3889
3890$(document).on('click', '[data-js="copy_site"]', function() {
3891    let _this = $(this),
3892        url = $(document).find('[name="basket_share"]').val();
3893
3894    navigator.clipboard.writeText(url);
3895    _this.text('Ссылка скопирована')
3896});
3897
3898
3899
3900/*тинькоф авторизация редирект*/
3901// Функция для установки куки
3902function setCookie(name, value, days) {
3903    const expires = new Date();
3904    expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
3905    document.cookie = name + '=' + encodeURIComponent(value) + ';expires=' + expires.toUTCString();
3906}
3907
3908// Функция для получения текущего URL
3909function getCurrentUrl() {
3910    return window.location.href;
3911}
3912
3913function eventAddBasket(ELEMENT_ID,QUANTITY){
3914
3915    $.ajax({
3916        type: "POST",
3917        url: "/local/components/art-fresh/sale.basket/ajax_new.php",
3918        data: {action:"add",ELEMENT_ID:ELEMENT_ID,QUANTITY:QUANTITY},
3919        timeout: 15000,
3920        beforeSend: function () {
3921
3922        },
3923        success: function (data, textstatus) {
3924            const price = $(data).find(`[data-product-id=${ELEMENT_ID}]`).data('price');
3925
3926            obProduct.productAdded(ELEMENT_ID, true);
3927            
3928                $('.icon-link.cart-link span').html(data);
3929                $('.link-cart span').html(data);
3930            //obBasket.changeBasket(data);
3931
3932
3933            obProduct.productShowPopup(ELEMENT_ID, false, QUANTITY, price);
3934
3935            var BoxBasket = $("[data-box-basket]");
3936            if(!BoxBasket.hasClass("active"))
3937            {
3938                BoxBasket.addClass("active");
3939            }
3940            if (typeof gtm != "undefined") {
3941
3942                gtm.quantity = QUANTITY;
3943                dataLayer.push({
3944                    "ecommerce": {
3945                        'currencyCode': 'RUB',
3946                        "add": {
3947                            "products": [gtm]
3948                        }
3949                    },
3950                    'goods_id': gtm.id,
3951                    'goods_price': gtm.price,
3952                    'page_type': 'add_product',
3953                    'event': 'pixel-mg-event',
3954                    'pixel-mg-event-category': 'Enhanced Ecommerce',
3955                    'pixel-mg-event-action': 'Adding a Product to a Shopping Cart',
3956                    'pixel-mg-event-non-interaction': 'False'
3957
3958                });
3959
3960            }
3961        },
3962        error: function () {
3963            $obParent.removeClass("loading");
3964        }
3965    });
3966}
3967$(document).ready(function(){
3968    $(document).on("click",".price-line-butt a",function(e){
3969        e.preventDefault();
3970        parent=$(e.target).parents(".sku");
3971        let skuId= $(parent).data("sku-id");
3972        eventAddBasket(skuId,1)
3973    })
3974
3975    $(document).on("click",".card-item-basket-controls .input-box-bnt-minus",function(e){
3976        e.preventDefault();
3977        var val = parseInt($(this).parent().children('input').val());
3978        val = val - 1;
3979        if(val<1){val=1;}
3980        $(this).parent().children('input').val(val);
3981        /*parent=$(e.target).parents(".sku");
3982        let skuId= $(parent).data("sku-id");
3983        eventAddBasket(skuId,1)*/
3984    })
3985    $(document).on("click",".card-item-basket-controls .input-box-bnt-plus",function(e){
3986        e.preventDefault();
3987        var val = parseInt($(this).parent().children('input').val());
3988        val = val +1;
3989        $(this).parent().children('input').val(val);
3990        /*parent=$(e.target).parents(".sku");
3991        let skuId= $(parent).data("sku-id");
3992        eventAddBasket(skuId,1)*/
3993    })
3994
3995})
3996// Добавляем обработчик события клика на кнопку
3997if(typeof saveButton !== 'undefined')
3998{
3999    let saveButton;
4000}
4001saveButton = document.querySelector('.tid-box a');
4002saveButton?.addEventListener('click', function(event) {
4003    event.preventDefault();
4004    const currentUrl = getCurrentUrl();
4005    setCookie('savedUrlAutTinkof', currentUrl, 365); // Записываем URL в куки на 365 дней
4006
4007});
4008
4009/*тинькоф авторизация редирект Конец*/
4010
4011
4012window.digiLayer = {
4013
4014    addToCart: function(offer_id, amount = 1, self) {
4015        return new Promise((resolve, reject) => {
4016            let iProductID = offer_id;
4017            let iQuantity = amount;
4018            let obData = {action: "add", "ELEMENT_ID": iProductID, "QUANTITY": iQuantity};
4019            $.ajax({
4020                type: "POST",
4021                url: "/local/components/art-fresh/sale.basket/ajax_new.php",
4022                data: obData,
4023                timeout: 15000,
4024                success: function (data, textstatus) {
4025
4026                    obProduct.productAdded(iProductID, true);
4027                    
4028                $('.icon-link.cart-link span').html(data);
4029                $('.link-cart span').html(data);
4030                    //obBasket.changeBasket(data);
4031                    obProduct.productShowPopup(iProductID, false, iQuantity);
4032
4033                    var BoxBasket = $("[data-box-basket]");
4034                    if(!BoxBasket.hasClass("active"))
4035                    {
4036                        BoxBasket.addClass("active");
4037                    }
4038
4039                    $.ajax({
4040                        url: '/local/ajax/getProduct.php',
4041                        dataType: 'html',
4042                        data: {
4043                            'id': iProductID,
4044                        },
4045                        type: 'POST',
4046                        success: function (data) {
4047
4048                            var dataJSON = JSON.parse(data);
4049                            dataLayer.push({
4050                                "ecommerce": {
4051                                    'currencyCode': 'RUB',
4052                                    "add": {
4053                                        "products": [{
4054                                            "id": iProductID,
4055                                            "name": dataJSON.name,
4056                                            "brand": dataJSON.brand,
4057                                            "category": dataJSON.category,
4058                                            "price": dataJSON.price,
4059                                            "variant": dataJSON.variant,
4060                                            "quantity": iQuantity
4061                                        }]
4062                                    }
4063                                },
4064                                'goods_id': iProductID,
4065                                'goods_price': dataJSON.price,
4066                                'page_type': 'add_product',
4067                                'event': 'pixel-mg-event',
4068                                'pixel-mg-event-category': 'Enhanced Ecommerce',
4069                                'pixel-mg-event-action': 'Adding a Product to a Shopping Cart',
4070                                'pixel-mg-event-non-interaction': 'False'
4071
4072                            });
4073                        },
4074                        timeout: 2000
4075                    });
4076
4077                },
4078                error: function () {
4079
4080                }
4081            });
4082
4083            resolve(true); // Возвращаем promise с true после успешного добавления в корзину
4084        });
4085    },
4086// Функция уменьшения количества товара в корзине на указанное amount
4087removeFromCart: function(sku_id, amount) {
4088    return new Promise((resolve, reject) => {
4089        if (!sku_id) {
4090            reject(new Error('SKU_ID не передан'));
4091            return;
4092        }
4093
4094        // Если amount не передан или меньше 1, полностью удаляем товар
4095        if (!amount || amount < 1) {
4096            amount = 0;
4097        }
4098
4099        $.ajax({
4100            type: "POST",
4101            url: "/local/components/art-fresh/sale.basket/ajax_new.php",
4102            data: {
4103                action: "decrease",  // новое действие
4104                SKU_ID: sku_id,
4105                AMOUNT: amount      // количество для уменьшения
4106            },
4107            timeout: 15000,
4108            success: function (data, textstatus) {
4109                // Обновляем счетчики корзин
4109ы
4110                $('.icon-link.cart-link span').html(data);
4111                $('.link-cart span').html(data);
4112                
4113                resolve(true);
4114            },
4115            error: function (xhr, status, error) {
4116                reject(error || status);
4117            }
4118        });
4119    });
4120},
4121    // Функция получения состояния корзины
4122    cartState: function() {
4123        return new Promise((resolve, reject) => {
4124            $.ajax({
4125                type: "GET",
4126                url: "/local/components/art-fresh/sale.basket/ajax_new.php",
4127                data: {
4128                    action: "get"
4129                },
4130                timeout: 15000,
4131                success: function (response) {
4132                    // Предполагаем, что ответ приходит в формате:
4133                    // { "PRODUCT_ID_1": "количество", "PRODUCT_ID_2": "количество", ... }
4134                    // или массив объектов с id и quantity
4135                    
4136                    let cartData = {};
4137                    
4138                    // Если ответ - строка с JSON, парсим
4139                    if (typeof response === 'string') {
4140                        try {
4141                            response = JSON.parse(response);
4142                        } catch (e) {
4143                            reject(new Error('Ошибка парсинга ответа сервера'));
4144                            return;
4145                        }
4146                    }
4147                    
4148                    // Если ответ - массив товаров в корзине
4149                    if (Array.isArray(response)) {
4150                        response.forEach(function(item) {
4151                            if (item.ID || item.PRODUCT_ID || item.SKU_ID) {
4152                                const id = item.ID || item.PRODUCT_ID || item.SKU_ID;
4153                                const quantity = parseInt(item.QUANTITY) || 0;
4154                                if (quantity > 0) {
4155                                    cartData[id] = quantity;
4156                                }
4157                            }
4158                        });
4159                    } 
4160                    // Если ответ - объект вида {id: quantity}
4161                    else if (typeof response === 'object' && response !== null) {
4162                        Object.keys(response).forEach(function(key) {
4163                            const quantity = parseInt(response[key]) || 0;
4164                            if (quantity > 0) {
4165                                cartData[key] = quantity;
4166                            }
4167                        });
4168                    }
4169                    
4170                    resolve(cartData);
4171                },
4172                error: function (xhr, status, error) {
4173                    reject(error || status);
4174                }
4175            });
4176        });
4177    },
4178    addToFavorites: function (offer_id) {
4179        const id = String(offer_id);
4180
4181        return new Promise((resolve, reject) => {
4182            $.ajax({
4183                type: 'POST',
4184                url: FavoriteManager.url,
4185                data: {
4186                    PRODUCT_ID: id
4187                },
4188                success: function () {
4189                    FavoriteManager.itemId = id;
4190                    FavoriteManager.changeClass();
4191
4192                    if (!window.siteState.favorites.includes(id)) {
4193                        window.siteState.favorites.push(id);
4194                    }
4195
4196                    resolve(true);
4197                },
4198                error: function (xhr, status, error) {
4199                    reject(error || status);
4200                }
4201            });
4202        });
4203    },
4204
4205    removeFromFavorites: function (offer_id) {
4206        const id = String(offer_id);
4207
4208        return new Promise((resolve, reject) => {
4209            if (!window.siteState.favorites.includes(id)) {
4210                resolve(true);
4211                return;
4212            }
4213
4214            $.ajax({
4215                type: 'POST',
4216                url: FavoriteManager.url,
4217                data: {
4218                    PRODUCT_ID: id
4219                },
4220                success: function () {
4221                    FavoriteManager.itemId = id;
4222                    FavoriteManager.changeClass();
4223
4224                    window.siteState.favorites = window.siteState.favorites.filter(function (item) {
4225                        return item !== id;
4226                    });
4227
4228                    resolve(true);
4229                },
4230                error: function (xhr, status, error) {
4231                    reject(error || status);
4232                }
4233            });
4234        })
4235    },
4236
4237    favoritesState: function () {
4238        return Promise.resolve(window.siteState.favorites);
4239    },
4240
4241    addToCompare: function (offer_id) {
4242        const id = String(offer_id);
4243
4244        return new Promise((resolve, reject) => {
4245            $.ajax({
4246                type: 'POST',
4247                url: CompareManager.url,
4248                data: {
4249                    action: 'add',
4250                    ID: id
4251                },
4252                success: function () {
4253                    CompareManager.itemId = id;
4254                    CompareManager.changeClass();
4255
4256                    if (!window.siteState.compare.includes(id)) {
4257                        window.siteState.compare.push(id);
4258                    }
4259
4260                    resolve(true);
4261                },
4262                error: function (xhr, status, error) {
4263                    reject(error || status);
4264                }
4265            });
4266        });
4267    },
4268
4269    removeFromCompare: function (offer_id) {
4270        const id = String(offer_id);
4271
4272        return new Promise((resolve, reject) => {
4273            $.ajax({
4274                type: 'POST',
4275                url: CompareManager.url,
4276                data: {
4277                    action: 'remove',
4278                    ID: id
4279                },
4280                success: function () {
4281                    CompareManager.itemId = id;
4282                    CompareManager.changeClass();
4283
4284                    window.siteState.compare = window.siteState.compare.filter(function (item) {
4285                        return item !== id;
4286                    });
4287
4288                    resolve(true);
4289                },
4290                error: function (xhr, status, error) {
4291                    reject(error || status);
4292                }
4293            });
4294        });
4295    },
4296
4297    compareState: function () {
4298        return Promise.resolve(window.siteState.compare);
4299    },
4300};
4301
4302$(document).ready(function() {
4303    /* $('.roistat-phone-tel').text('+7 (499) 519-13-00');
4304     $('.track_tel').text('+7 (499) 519-13-00');
4305     $('.header-main .cart').attr('href', '+74995191300');
4306     $('.foot_phone a').attr('href', '+74995191300');*/
4307    $.mask.definitions['h'] = "[1|2|3|4|5|6|9]";
4308    $('[name="form_text_71"]').mask("+7 (h99) 999-99-99");
4309    $('#phone').mask("+7 (h99) 999-99-99");
4310
4311    $('[name="tk_delivery_number"]').mask("+7 (h99) 999-99-99");
4312});
4313$(document).ready(function() {
4314    $('.reviewsList_slider').slick({
4315        dots: true,
4316        arrows: false
4317    });
4318});
4319
4320
4321
4322
4323var obSpolerBoxs = document.querySelectorAll('.spoiler-box'),
4324    indexObSpoler, obSpolerBox;
4325
4326for (indexObSpoler = 0; indexObSpoler < obSpolerBoxs.length; indexObSpoler++) {
4327    obSpolerBox = obSpolerBoxs[indexObSpoler];
4328    obSpolerBox.addEventListener('click', clickHandler);
4329
4330}
4331
4332function clickHandler(event) {
4333    event.preventDefault();
4334    this.classList.toggle("spoiler-box-active")
4335
4336}
4337
4338
4339function clickHandlerFaq(event) {
4340    event.preventDefault();
4341    this.classList.toggle("faqItem__title-active");
4342    toggleBox = this.parentNode.querySelector(".faqItem__answer-toggle")
4343
4344    toggleBox.classList.toggle("faqItem__answer-toggle-active");
4345    if (toggleBox.classList.contains("faqItem__answer-toggle-active")) {
4346        height = toggleBox.querySelector(".faqItem__answer").offsetHeight
4347    }
4348    else {
4349        height = 0;
4350    }
4351    toggleBox.style.height = height + 'px';
4352
4353}
4354var obSpolerBoxs = document.querySelectorAll('.faqItem')
4355for (indexObSpoler = 0; indexObSpoler < obSpolerBoxs.length; indexObSpoler++) {
4356    obSpolerBox = obSpolerBoxs[indexObSpoler].querySelector(".faqItem__title");
4357    obSpolerBox.addEventListener('click', clickHandlerFaq);
4358
4359}
4360
4361function updateDiscountProgress(currentAmount) {
4362    const maxAmount = 90000;    
4363    const stepone = 13;
4364    const progressFill = document.getElementById('discountProgress');
4365    
4366    // Проверка существования элемента
4367    if (!progressFill) return;
4368    
4369    let percentage;
4370    console.log(currentAmount);
4371    // Нелинейное распределение:
4372    // до 30000 → 2%
4373    // 50000 → 50%
4374    // 80000 → 100%
4375    if (currentAmount <= 0) {
4376        percentage = 0;
4377    } else if (currentAmount <= 30000) {
4378        percentage = (currentAmount / 30000) * stepone;
4379    } else if (currentAmount <= 50000) {
4380        percentage = stepone + ((currentAmount - 30000) / (50000 - 30000)) * (50 - stepone);
4381    } else if (currentAmount <= maxAmount) {
4382        percentage = 50 + ((currentAmount - 50000) / (maxAmount - 50000)) * (100 - 50);
4383    } else {
4384        percentage = 100;
4385    }
4386    
4387    // Применяем ширину заполнения
4388    progressFill.style.width = percentage + '%';
4389    
4390    // Обновляем классы active у процентов
4391    updatePercentActive(currentAmount);
4392}
4393
4394// Функция для обновления активных процентов
4395function updatePercentActive(currentAmount) {
4396    const percentItems = document.querySelectorAll('.limit-percent li');
4397    
4398    if (!percentItems.length) return;
4399    
4400    // Удаляем класс active у всех
4401    percentItems.forEach(item => {
4402        item.classList.remove('active');
4403    });
4404    
4405    // Активируем достигнутые пороги
4406    if (currentAmount >= 30000 && percentItems[0]) {
4407        percentItems[0].classList.add('active'); // -4%
4408    }
4409    if (currentAmount >= 50000 && percentItems[1]) {
4410        percentItems[1].classList.add('active'); // -6%
4411    }
4412    if (currentAmount >= 80000 && percentItems[2]) {
4413        percentItems[2].classList.add('active'); // -8%
4414    }
4415}

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.