PageSourceSearch

https://sartoreale.ru/local/components/mm/subscription.form/templates/.default/script.js?17800418668451

js sartoreale.ru collected 2026-09-24 20:29:59 UTC 8,451 bytes, 223 lines download raw bytes

1BX.ready(function() {
2    // Элементы формы
3    var formWrapper = BX('lh_desktop_smartoffer');
4    var form = BX('widget--form');
5    var submitBtn = BX('subscribe-submit');
6    var emailInput = BX('subscribe-email');
7    var successBlock = BX('widget--success-text');
8    var errorBlock = BX('widget--error-text');
9    var closeBtn = document.querySelector('#lh_desktop_smartoffer .widget--close');
10    var isAuthorized = document.querySelector('#lh_desktop_smartoffer input[name="user_authorized"]').value;
11    var formType = document.querySelector('#lh_desktop_smartoffer input[name="form_type"]').value;
12
13    // Если нет формы, выходим
14    if (!form) return;
15
16    // Состояние формы
17    var isSubmitting = false;
18
19    if (!getCookie('dcBannerShowed') && $(window).width() > 768) {
20        console.log('will open dcBanner');
21        setTimeout(function(){
22            formWrapper.style.display = 'block';
23            formWrapper.style.opacity = '1';
24        }, 5000);
25    }
26
27    // Обработчик отправки формы
28    BX.bind(form, 'submit', function(e) {
29        e.preventDefault();
30
31        // Предотвращаем двойную отправку
32        if (isSubmitting) return;
33
34        // Получаем email
35        var email = emailInput ? emailInput.value.trim() : '';
36
37        // Валидация email
38        if (!validateEmail(email)) {
39            showError('Пожалуйста, введите корректный e-mail');
40            return;
41        }
42
43        // Проверяем согласия
44        var agreement = BX('agreement-val');
45        var adsAgreement = BX('ads-agreement-val');
46
47        if (!agreement || !agreement.checked) {
48            showError('Необходимо дать согласие на обработку персональных данных');
49            return;
50        }
51
52        if (!adsAgreement || !adsAgreement.checked) {
53            showError('Необходимо дать согласие на получение рассылок');
54            return;
55        }
56
57        // Блокируем форму
58        isSubmitting = true;
59        submitBtn.disabled = true;
60        BX.addClass(submitBtn, 'loading');
61
62        // Скрываем предыдущие сообщения
63        hideMessages();
64
65        // 1. Отправляем в Maxma через ClTrack, если клиент не авторизован
66        if (!isAuthorized) {
67            sendToMaxma(email, formType);
68        }
69
70        // 2. Отправляем в веб-форму Битрикс (исправленный URL)
71        saveToBitrix(email, isAuthorized, formType);
72    });
73
74    // Функция отправки в Maxma
75    function sendToMaxma(email, formType) {
76        // Отправляем addClientInfo
77        if (typeof ClTrack !== 'undefined') {
78            try {
79                if (typeof ClTrack === 'function') {
80                    ClTrack('addClientInfo', {
81                        email: email,
82                        subscribed: true,
83                        formType: formType
84                    });
85                    console.log('Maxma: addClientInfo sent', email);
86                }
87            } catch (e) {
88                console.warn('Maxma error:', e);
89            }
90        }
91    }
92
93    // Сохранение в БД Битрикс
94    function saveToBitrix(email, isAuthorized, formType) {
95        // Создаем объект с данными для JSON
96        var data = {
97            sessid: BX.bitrix_sessid(),
98            email: email,
99            action: 'subscribe',
100            web_form_id: '6',
101            isAuthorized: isAuthorized,
102            formType: formType
103        };
104
105        BX.ajax({
106            url: '/local/components/mm/subscription.form/templates/.default/ajax.php',
107            method: 'POST',
108            data: data,
109            processData: true,
110            contentType: 'application/x-www-form-urlencoded',
111            timeout: 30,
112            headers: [
113                {'X-Requested-With': 'XMLHttpRequest'}
114            ],
115            onsuccess: function(response) {
116                try {
117                    // Если response уже объект (при использовании BX.ajax с dataType)
118                    var data = typeof response === 'object' ? response : JSON.parse(response);
119
120                    if (data.success) {
121                        console.log('Direct AJAX success - форма добавлена');
122                        handleSuccess(email);
123                    } else {
124                        console.warn('Direct AJAX failed:', data.message || 'Unknown error');
125                        handleSuccess(email);
126                    }
127                } catch (e) {
128                    console.warn('Invalid response:', e);
129                    console.warn('Raw response:', response);
130                    handleSuccess(email);
131                }
132            },
133            onfailure: function(error) {
134                console.warn('Direct AJAX connection failed:', error);
135                handleSuccess(email);
136            }
137        });
138    }
139
140    // Локальное логирование (без addEvent)
141    function saveToLocalLog(email) {
142        // Просто логируем в консоль
143        console.log('Subscription saved for:', email);
144
145        // Можно сохранить в localStorage для статистики
146        var subscriptions = JSON.parse(localStorage.getItem('subscriptions') || '[]');
147        subscriptions.push({
148                        email: email,
149            date: new Date().toISOString()
150                    });
151        localStorage.setItem('subscriptions', JSON.stringify(subscriptions));
152    }
153
154    // Обработка успеха
155    function handleSuccess(email) {
156        // Разблокируем форму
157        isSubmitting = false;
158        submitBtn.disabled = false;
159        BX.removeClass(submitBtn, 'loading');
160
161        setCookie('dcBannerShowed', true, { expires: 365 });
162
163        // Скрываем форму, показываем успех
164        if (form && successBlock) {
165            form.style.display = 'none';
166            document.getElementsByClassName('widget--title')[0].style.display = 'none';
167            document.getElementsByClassName('widget--text')[0].style.display = 'none';
168            successBlock.style.display = 'block';
169
170            // Через 3 секунды закрываем форму
171            setTimeout(function() {
172                if (form && successBlock) {
173                    document.getElementsByClassName('widget--close')[0].click();
174                    document.getElementsByClassName('lhWidgetItem changed')[0].remove();
175                }
176            }, 3000);
177        }
178    }
179
180    // Показать ошибку
181    function showError(message) {
182        if (errorBlock) {
183            var errorMessage = errorBlock.querySelector('.error-message');
184            if (errorMessage) {
185                errorMessage.textContent = message;
186            }
187            errorBlock.style.display = 'block';
188
189            // Разблокируем форму
190            isSubmitting = false;
191            submitBtn.disabled = false;
192            BX.removeClass(submitBtn, 'loading');
193
194            // Автоматически скрываем через 5 секунд
195            setTimeout(hideMessages, 5000);
196        } else {
197            alert(message);
198        }
199    }
200
201    // Скрыть все сообщения
202    function hideMessages() {
203        if (successBlock) successBlock.style.display = 'none';
204        if (errorBlock) errorBlock.style.display = 'none';
205    }
206
207    // Валидация email
208    function validateEmail(email) {
209        var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
210        return re.test(email);
211    }
212
213    // Закрытие виджета
214    if (closeBtn) {
215        BX.bind(closeBtn, 'click', function() {
216            var widget = BX('lh_desktop_smartoffer');
217            if (widget) {
218                widget.style.display = 'none';
219            }
220		    setCookie('dcBannerShowed', true, { expires: 1, path: '/' });
221        });
222    }
223});

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.