PageSourceSearch

https://riolux.ru/js/MyAll.js?ver=29

js riolux.ru collected 2026-10-05 18:11:33 UTC 99,042 bytes, 2,530 lines download raw bytes

1/* Валидация форм */
2const notCheckedClass = 'Reqfield_not_checked';
3// проверка валидации
4function checkFormValidation(requiredInputClass, form) {
5    return $(document).find(`#${form} .${requiredInputClass}, .${requiredInputClass}[form="${form}"]`).length === 0;
6}
7
8function isRequiredFieldChecked(form, currentField) {
9    let result;
10    let inputType = currentField.attr('type');
11    let domSelector = `input[name="${currentField.attr('name')}"]`;
12
13    switch (inputType) {
14        case 'radio':
15        case 'checkbox':
16            let checkedField = $(`#${form} ${domSelector}:checked, ${domSelector}[form="${form}"]:checked`);
17            result = !(checkedField.length === 0 || checkedField.val().length === 0);
18            break;
19        case 'text':
20            result = currentField.val().length !== 0;
21            break;
22        default:
23            result = !(currentField.prop('tagName') === 'SELECT' && !currentField.find('option:selected').val());
24            break;
25    }
26
27    return result;
28}
29
30function checkField(form, currentField, getResult = false) {
31    let result;
32    let inputType = currentField.attr('type');
33    let dom_selector = `input[name="${currentField.attr('name')}"]`;
34
35    switch (inputType) {
36        case 'radio':
37        case 'checkbox':
38            let checkedField = $(`#${form} ${dom_selector}:checked, ${dom_selector}[form="${form}"]:checked`);
39            if (checkedField.length === 0 || checkedField.val().length === 0) {
40                //vv//
41                if (currentField.hasClass('Required_sibling')) {
42                    let siblingName = currentField.data('sibling-name');
43                    // let siblingFields = $(`input.Required_sibling[data-sibling-name="${siblingName}"]`);
44                    let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);
45                    let checked_fields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"]:checked, input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]:checked`);  // Выбор родственных полей
46                    if (!checked_fields.length) {
47                        siblingFields.addClass(notCheckedClass);
48                    }
49                } else {
50                    currentField.addClass(notCheckedClass);
51                }
52                //^^//
53                //                    currentField.addClass(notCheckedClass);
54                $(`#${form} ${dom_selector}, ${dom_selector}[form="${form}"]`).parents('.multiselect').addClass(`${notCheckedClass}`);
55                result = false;
56            } else {
57                //vv//
58                if (currentField.hasClass('Required_sibling')) {
59                    let siblingName = currentField.data('sibling-name');
60                    let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);
61                    siblingFields.removeClass(notCheckedClass);
62                }
63                //^^//
64                $(`#${form} ${dom_selector}, ${dom_selector}[form="${form}"]`).parents('.multiselect').removeClass(`${notCheckedClass}`);
65                result = true;
66            }
67            break;
68
69        case 'text':
70            if (currentField.val().length === 0) {
71                if (currentField.hasClass('Required_sibling')) {
72                    let siblingName = currentField.data('sibling-name');
73                    // let siblingFields = $(`input.Required_sibling[data-sibling-name="${siblingName}"]`);
74                    let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);
75                    const atLeastOneNotEmpty = elements => [...elements].some(el => el.value.trim());
76                    if (atLeastOneNotEmpty(siblingFields)) {
77                        currentField.removeClass(notCheckedClass);
78                    } else {
79                        siblingFields.addClass(notCheckedClass);
80                    }
81                } else {
82                    currentField.addClass(notCheckedClass);
83                }
84                result = false;
85            } else {
86                if (currentField.hasClass('Required_sibling')) {
87                    let siblingName = currentField.data('sibling-name');
88                    let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);
89                    siblingFields.removeClass(notCheckedClass);
90                }
91                result = true;
92            }
93            break;
94
95        default:
96            if (currentField.prop('tagName') === 'SELECT' && !currentField.find('option:selected').val()) {
97                currentField.addClass(notCheckedClass);
98                result = false;
99            } else {
100                result = true;
101            }
102            break;
103    }
104    if (getResult) {
105        return result;
106    }
107}
108
109function hasNonEmptySiblings(form, field) {
110    let siblingName = field.data('sibling-name');
111    // let siblingFields = $(`input.Required_sibling[data-sibling-name="${siblingName}"]`);
112    let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);
113    const atLeastOneNotEmpty = elements => [...elements].some(el => el.value.trim());
114    return atLeastOneNotEmpty(siblingFields);
115}
116
117function handleParents(form, parentField) {
118    let notCheckedHidChildClass = 'Nc_hid_required_child';
119    let checkedHidChildClass = 'C_hid_required_child';
120    if (parentField.attr('type') === 'radio') {
121        let sameRadioInputs = $(`#${form} input[name="${parentField.attr('name')}"], input[name="${parentField.attr('name')}"][form="${form}"]`);
122        sameRadioInputs.each(function (index, input) {
123            if ($(input).hasClass('Required_parent')) {
124                let parentName = $(input).data('parent-name');
125                let children = $(`#${form} .Required_child[data-parent-name="${parentName}"], .Required_child[data-parent-name="${parentName}"][form="${form}"]`);
126                children.each(function (index, child) {
127                    if ($(child).is(":visible")) {
128                        if ($(child).hasClass(notCheckedHidChildClass)) {
129                            $(child).removeClass(notCheckedHidChildClass);
130                            $(child).addClass(notCheckedClass);
131                        } else {
132                            $(child).removeClass(checkedHidChildClass);
133                        }
134                    }
135                });
136            }
137        });
138    }
139    if (parentField.hasClass('Required_parent')) {
140        let parentName = parentField.data('parent-name');
141        // let childs = $(`.Required_child[data-parent-name="${parentName}"]`);
142        let children = $(`#${form} .Required_child[data-parent-name="${parentName}"], .Required_child[data-parent-name="${parentName}"][form="${form}"]`);
143        let isParentChecked = isRequiredFieldChecked(form, parentField);
144        children.each(function (index, child) {
145            if (isParentChecked) {
146                // if ($(child).is(":visible")) {
147                if ($(child).hasClass(notCheckedClass)) {
148                    $(child).removeClass(notCheckedClass);
149                    $(child).addClass(notCheckedHidChildClass);
150                } else {
151                    $(child).addClass(checkedHidChildClass);
152                }
153                // }
154            } else {
155                $(child).removeClass(notCheckedHidChildClass);
156                $(child).removeClass(checkedHidChildClass);
157                if ($(child).hasClass('Required_sibling') && hasNonEmptySiblings(form, $(child))) {
158                    return true;
159                }
160                if (!isRequiredFieldChecked(form, $(child)) && !$(child).hasClass('Required_field_no')) {
161                    $(child).addClass(notCheckedClass);
162                }
163            }
164        });
165    }
166}
167
168function requiredRadio(elem, form) {
169    let checkedField = $(`#${form} input[name="${elem.attr('name')}"]:checked, input[name="${elem.attr('name')}"][form="${form}"]:checked`);
170    let sameNameFields = $(`#${form} input[name="${elem.attr('name')}"], input[name="${elem.attr('name')}"][form="${form}"]`);
171    if (checkedField.length && checkedField.val().length) {
172        sameNameFields.removeClass(notCheckedClass).parents('.multiselect').removeClass(`${notCheckedClass}`);
173    } else {
174        sameNameFields.addClass(notCheckedClass).parents('.multiselect').addClass(`${notCheckedClass}`);
175    }
176    handleParents(form, elem);
177}
178
179function requiredCheckbox(elem, form) {
180    // if ($(`#${form} input[name="${elem.attr('name')}"]:checked, input[name="${elem.attr('name')}"][form="${form}"]:checked`).length) {
181    //     $(`#${form} input[name="${elem.attr('name')}"], input[name="${elem.attr('name')}"][form="${form}"]`).removeClass(notCheckedClass);
182    // }
183    let checkedField = $(`#${form} input[name="${elem.attr('name')}"]:checked, input[name="${elem.attr('name')}"][form="${form}"]:checked`);
184    let sameNameFields = $(`#${form} input[name="${elem.attr('name')}"], input[name="${elem.attr('name')}"][form="${form}"]`);
185    if (checkedField.length && checkedField.val().length) {
186        sameNameFields.removeClass(notCheckedClass).parents('.multiselect').removeClass(`${notCheckedClass}`);
187        //vv//
188        if (elem.hasClass('Required_sibling')) {  // Проверка если поле имеет родственные поля
189            let siblingName = elem.data('sibling-name');
190            let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);  // Выбор родственных полей
191            siblingFields.removeClass(notCheckedClass);
192        }
193        //^^//
194    } else {
195        //        sameNameFields.addClass(notCheckedClass).parents('.multiselect').addClass(`${notCheckedClass}`);
196        //vv//
197        if (elem.hasClass('Required_sibling')) {  // Проверка если поле имеет родственные поля
198            let siblingName = elem.data('sibling-name');
199            let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);  // Выбор родственных полей
200            // Проверка что хотя бы одно родственное поле заполнено
201            // если нет таких, то проставляем им класс notChecked
202            let checked_fields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"]:checked, input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]:checked`);  // Выбор родственных полей
203            if (!checked_fields.length) {
204                siblingFields.addClass(notCheckedClass);
205            }
206        } else {
207            sameNameFields.addClass(notCheckedClass).parents('.multiselect').addClass(`${notCheckedClass}`);
208        }
209        //^^//
210    }
211}
212
213function requiredSelect(elem, form) {
214    if (elem.selectedOptions[0].value !== '') {
215        $(elem).removeClass(notCheckedClass);
216    } else {
217        $(elem).addClass(notCheckedClass);
218    }
219}
220
221function requiredText(elem, form) {
222    if (elem.hasClass('Nc_hid_required_child') || elem.hasClass('C_hid_required_child')) {  // Не проверять для отключенных связанных полей
223        return;
224    }
225
226    if (elem.val() !== '') {  // Обязательное поле не пустое
227        elem.removeClass(notCheckedClass);
228        if (elem.hasClass('Required_sibling')) {  // Проверка если поле имеет родственные поля
229            let siblingName = elem.data('sibling-name');
230            let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);  // Выбор родственных полей
231            siblingFields.removeClass(notCheckedClass);
232        }
233    } else {  // Если обязательное поле пустое
234        if (elem.hasClass('Required_sibling')) {  // Проверка если поле имеет родственные поля
235            let siblingName = elem.data('sibling-name');
236            let siblingFields = $(`#${form} input.Required_sibling[data-sibling-name="${siblingName}"], input.Required_sibling[data-sibling-name="${siblingName}"][form="${form}"]`);  // Выбор родственных полей
237            // Проверка что хотя бы одно родственное поле заполнено
238            // если нет таких, то проставляем им класс notChecked
239            const atLeastOneNotEmpty = elements => [...elements].some(el => el.value.trim());
240            if (!atLeastOneNotEmpty(siblingFields)) {
241                siblingFields.addClass(notCheckedClass);
242            }
243        } else {
244            elem.addClass(notCheckedClass);
245        }
246    }
247}
248
249function checkFormRequiredFields(form_selector) {//TODO: Возможно её можно везде использовать
250    let inputs = $(`#${form_selector} .Required_field, [form="${form_selector}"].Required_field`);
251    inputs.each(function (index, element) {
252        checkField(form_selector, $(element));
253    });
254    inputs.each(function (index, element) {
255        handleParents(form_selector, $(element));
256    });
257}
258function showValidationPopup(message) {
259    const validationPopup = $('#validation_popup');
260
261    validationPopup.html(message);
262    validationPopup.addClass('active');
263
264    setTimeout(function () {
265        validationPopup.removeClass('active');
266    }, 4000);
267}
268
269// Вывод незаполненных обязательных полей
270function showEmptyRequiredFields(fieldNotCheckedClass) {
271    // Получение лейблов полей по id
272    const fieldNamesTranslation = {
273        'typesale': 'Продажа или Аренда?',
274        'RenovationType': 'Тип ремонта',
275        'typerent': 'Продажа или Аренда?',
276        'second': 'Тип недвижимости',
277        'newbuilding': 'Тип недвижимости',
278        'shares': 'Тип недвижимости',
279        'TotalArea': 'Общая площадь',
280        'RoomArea': 'Площадь комнаты',
281        'Floor': 'Этаж',
282        'NumberOfFloors': 'Количество этажей',
283        'ObjectPrice': 'Цена',
284        'n_one': 'Количество комнат',
285        'n_two': 'Количество комнат',
286        'n_tree': 'Количество комнат',
287        'n_four': 'Количество комнат',
288        'n_five': 'Количество комнат',
289        'n_six': 'Количество комнат',
290        'chk1': 'Количество комнат',
291        'chk2': 'Количество комнат',
292        'Ownership': 'Право собственности',
293        'WallMaterial': 'Материал стен/Тип дома',
294        // Карта
295        'BalconyNumber': 'Кол-во балконов',
296        'LoggiaNumber': 'Кол-во лоджий',
297        'RoomType': 'Тип комнат',
298        'KitchenArea': 'Площадь кухни',
299        'LivingArea': 'Площадь жилой',
300        // Аренда квартиры
301        'ShareAmount': 'Размер доли в квартире/доме',
302        'query': 'Адрес',
303        'ClientCommission': 'Комиссия клиента',
304        'DepositSum': 'Сумма депозита',
305        'RentTime': 'Срок аренды',
306        'LeaseDeposit': 'Залог',
307        // Коммерческая
308        'office': 'Тип недвижимости',
309        'PriceForCian': 'Цена за (Циан)',
310        'PriceFor': 'Цена за (Авито)',
311        'VatType': 'Тип НДС',
312        'LandArea': 'Площадь земельного участка',
313        'StatusLand': 'Категория земли',
314        'AgentCommission': 'Комиссия агента',
315        'BuildingEnter': 'Вход в здание',
316        'ContractType': 'Тип договора',
317        'DirectRental': 'Параметры аренды',
318        'SubRental': 'Параметры аренды',
319        'LayoutCian': 'Планировка',
320        'ConditionType': 'Отделка/Состояние',
321        // Загородная
322        'StatusLands': 'Категория земли',
323        'MeasurementUnit': 'Единицы измерения',
324        'BuildingArea': 'Площадь Дома',
325
326        // контакты
327        'contact[Name]': 'Ваше имя',
328        'contact[Phone]': 'Ваш телефон',
329
330        'pass_birthdate': 'Дата рождения',
331    };
332    // Массив со значениями лейблов обязательных незаполненных полей
333    let emptyFieldNames = [];
334
335    // Заполнение массива значений лейблов
336    $(fieldNotCheckedClass).each(function (index, element) {
337        let inputId = $(element).attr('id');
338        let custom_name = $(element).data('name');
339
340        if (!inputId || !(inputId in fieldNamesTranslation)) {
341            inputId = $(element).attr('name');
342        }
343
344        const inputTranslation = fieldNamesTranslation[inputId];
345        if (inputTranslation && !emptyFieldNames.includes(inputTranslation)) {
346            emptyFieldNames.push(inputTranslation);
347        } else if (custom_name && !emptyFieldNames.includes(custom_name)) {
348            emptyFieldNames.push(custom_name);
349        }
350    });
351
352    if (emptyFieldNames.length) {
353        let fieldsList = '<ul class="empty_reqired_fields">';
354        emptyFieldNames.forEach(function (field) {
355            fieldsList += '<li>' + field + '</li>';
356        });
357        fieldsList += '</ul>';
358        let message = '<p>Не заполнены следующие поля:</p>' + fieldsList;
359
360        showValidationPopup(message);
361    }
362}
363
364$(document).ready(function () {
365    $(document).on('mouseenter mouseleave', '.MenuS', function (event) {
366        if (event.type === 'mouseenter') {
367            $(this).addClass('active');
368        } else {
369            $(this).removeClass('active');
370        }
371    });
372});
373
374/* Сортировка таблицы "объекты" */
375$(document).ready(function () {
376    if ($(location).attr('href').match('category') !== null) {
377        $(document).on('click', 'th.table_column_sort', function () {
378            const columnBDName = $(this).data('prop');
379            const sortOrderInput = $('#sortOrder');
380            const columnName = $('#columnName');
381
382            // Если имя колоннки уже имеется, меняем порядок
383            if (columnName.val() && columnName.val() === columnBDName) {
384                if (sortOrderInput.val() === 'desc') {
385                    sortOrderInput.val('asc');
386                } else {
387                    sortOrderInput.val('desc');
388                }
389            } else {
390                columnName.val(columnBDName);
391                sortOrderInput.val('desc');
392            }
393
394            getObjects();
395        });
396    }
397});
398/* Сортировка таблицы "объекты" */
399
400/* Редактирование полей */
401$(document).on('click', '.editable-field-container.input-type', function (e) {
402    // Не открывать fast view по клику на редактируемое поле
403    e.stopPropagation();
404    // .editable-field
405    let editableField = $(this).find('.editable-field');
406    const objectId = $(editableField).data('id');
407    const objectColumn = $(editableField).data('column');
408
409    const $editableField = $(editableField);
410
411    let $self = $(this);
412    // Настройки для формы
413    this.config = {
414        editForm: {
415            id: 'editableFieldForm',
416            class: 'editableFieldForm',
417            action: '/',
418            method: 'POST',
419        },
420        editField: '<input class="EditInput" name="editElement" type="text" autocomplete="off" />',
421        submitBtn: '<button type="submit" class="save-btn"><i class="fas fa-check"></i></button>',
422        cancelBtn: '<button type="button" class="cancel-btn"><i class="fas fa-times"></i></button>',
423        objectIdInput: '<input name="obj_id" type="hidden" value="' + objectId + '">',
424        objectColumnInput: '<input name="column" type="hidden" value="' + objectColumn + '">',
425    };
426
427    this.initialValue = $(editableField).text().trim();
428
429    const editForm = $('<form></form>').attr(this.config.editForm); // форма для редактирования
430    const submitButton = $(this.config.submitBtn).addClass('button');
431    const cancelButton = $(this.config.cancelBtn).addClass('button inactive');
432    const editElement = $(this.config.editField).addClass('text');
433
434    editElement.val(this.initialValue);
435
436    editForm.append(editElement);
437
438    cancelButton.on('click', function () {
439        editForm.remove();
440        $editableField.show();
441        $self.find('.edit-hint').show();
442    });
443
444    submitButton.on('click', function () {
445        $self.find('.edit-hint').show();
446    });
447
448    const buttonsContainer = $('<div></div>').attr({'class': 'button-container'})
449        .append(submitButton).append(cancelButton);
450    editForm.append(buttonsContainer);
451    editForm.append(this.config.objectIdInput);
452    editForm.append(this.config.objectColumnInput);
453
454    $(this).find('.edit-hint').hide();
455    $editableField.hide().after(editForm);
456});
457$(document).on('click', '.editableFieldForm', function (e) {
458    e.stopPropagation();
459});
460$(document).on('submit', '.editableFieldForm', function (e) {
461    // остановка открытия fast view
462    e.stopPropagation();
463    e.preventDefault();
464
465    let $this = $(this);
466
467    let column = $(this).find('input[name = "column"]').val();
468    let obj_id = $(this).find('input[name = "obj_id"]').val();
469    let input_value = $(this).find('input[name = "editElement"]').val();
470    let data = column + '=' + input_value;
471    let url = '/card_update/';
472    // console.log(data);
473    $.ajax({
474        headers: {
475            'X-CSRF-TOKEN': $(
476                'meta[name=\"csrf-token\"]').attr('content')
477        },
478        url: url + obj_id,
479        type: "put",
480        datatype: "html",
481        data: data,
482        success: function () {
483            $('span[data-id="' + obj_id + '"][data-column="' + column + '"]').show().html(input_value);
484            $this.remove();
485        }
486    })
487});
488
489// Поля select
490$(document).on('click', '.editable-field-container.select-type', function (e) {
491    e.stopPropagation();
492    // .editable-field
493    let editableField = $(this).find('.editable-field');
494    let objectId = $(editableField).data('id');
495    let objectColumn = $(editableField).data('column');
496    let $editableField = $(editableField);
497    let $self = $(this);
498
499    // Настройки для формы
500    let config = {
501        editForm: {
502            id: 'editableFieldFormSelect',
503            class: 'editableFieldFormSelect',
504            action: '/',
505            method: 'POST',
506        },
507        editField: '<input class="EditInput" name="editElement" type="hidden" autocomplete="off" />',
508        selectField: '<select class="EditSelect"></select>',
509        objectIdInput: '<input name="obj_id" type="hidden" value="' + objectId + '">',
510        objectColumnInput: '<input name="column" type="hidden" value="' + objectColumn + '">',
511    };
512
513    // Создание формы для сохранения нового значения и передача параметров объекта
514    let editForm = $('<form></form>').attr(config.editForm);
515    let selectElement = $(config.selectField);
516    let editField = $(config.editField);
517
518    let optionValues;
519    // Параметры для селекта
520    switch (objectColumn) {
521        case 'mainId[Status]':
522            optionValues = [
523                'В работе',
524                'Под авансом',
525                'Продана',
526                'Отказ',
527                'Отложенный спрос',
528                'Черновик'
529            ];
530            break;
531        default:
532            break;
533    }
534    // Создание опций select'а
535    optionValues.forEach(function (value) {
536        let optionElement = $('<option ' + (value === editableField.text().trim() ? 'selected' : '')
537            + ' class="fast-selection" value="' + value + '">' + value + '</option>');
538        optionElement.on('click', function () {
539            editField.val(optionElement.val());
540            editForm.submit();
541        });
542        selectElement.append(optionElement);
543    });
544
545    // Формирование элементов формы
546    editForm.append(selectElement);
547    editForm.append(editField);
548    editForm.append(config.objectIdInput);
549    editForm.append(config.objectColumnInput);
550
551    $editableField.hide().after(editForm);
552});
553$(document).on('click', '.editableFieldFormSelect', function (e) {
554    e.stopPropagation();
555});
556$(document).on('submit', '.editableFieldFormSelect', function (e) {
557    // остановка открытия fast view
558    e.stopPropagation();
559    e.preventDefault();
560
561    let $this = $(this);
562
563    let column = $(this).find('input[name = "column"]').val();
564    let obj_id = $(this).find('input[name = "obj_id"]').val();
565    let input_value = $(this).find('input[name = "editElement"]').val();
566    let data = column + '=' + input_value;
567    let url = '/card_update/';
568    // console.log(data);
569
570    $.ajax({
571        headers: {
572            'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')
573        },
574        url: url + obj_id,
575        type: "put",
576        datatype: "html",
577        data: data,
578        success: function () {
579            $('span[data-id="' + obj_id + '"][data-column="' + column + '"]').show().html(input_value);
580            /* Поле "Статус" */
581            // обертка отвечающая за смену цветов поля "статус"
582            let statusFieldWrap = $this.closest('.Stat_table');
583            if (statusFieldWrap.length) {
584                // объект, связывающий значения полей и цветов
585                let statusFieldColors = {
586                    'В работе': 'status_color_vr',
587                    'Под авансом': 'status_color_podo',
588                    'Продана': 'status_color_p',
589                    'Отказ': 'status_color_otkaz',
590                    'Отложенный спрос': 'status_color_os',
591                };
592                // цикл, окрашивающий поле в соответствующий значению цвет
593                for (let selectValue in statusFieldColors) {
594                    let statusFieldColor = statusFieldColors[selectValue];
595                    if (input_value === selectValue) {
596                        statusFieldWrap.addClass(statusFieldColor);
597                    } else {
598                        statusFieldWrap.removeClass(statusFieldColor);
599                    }
600                }
601            }
602            /* Поле "Статус" */
603            $this.remove();
604        }
605    })
606});
607/* Редактирование полей */
608
609/*Выделение галочкой*/
610$(document).on('change', '#squaredFou1', function () {
611    $('#table_place .controls2').prop('checked', $(this).is(':checked'));
612    countShow();
613});
614
615let countChecked = function () {
616    let n = $(".controls2:checked").length;
617    $("#check_count").html(n + (n === 1 ? " выбран" : " выбраны"));
618    return n;
619};
620countChecked();
621// получаем id чекнутых
622let IdChecked = function () {
623    let all = $(".controls2:checked").map(function () {
624        return this.value;
625    }).get();
626    return all;
627};
628IdChecked();
629// показываем кол-во чекнутых
630let countShow = function () {
631    let count = countChecked();
632    if (count !== 0) {
633        $('#mass_red').removeClass('edit_menu_opacity');
634    } else {
635        $('#mass_red').addClass('edit_menu_opacity');
636    }
637}
638countShow();
639
640$(document).on('click', '.controls2', countShow);
641/*Выделение галочкой*/
642
643
644/**/
645
646/**/
647/*Еще фильтры*/
648$(document).ready(function () {
649    $('.AllFilters').click(function (event) {
650        $('.DopFilter,.DopFil').toggleClass('active');
651        $('.DopFilCheck').toggleClass('active');
652    });
653});
654/*Еще фильтры*/
655/*NB accord*/
656$(document).ready(function () {
657    let selected = null;
658    let mob = document.querySelector(".Mob");
659    if (mob) {
660        mob.addEventListener("click", event => {
661            if (event.target.closest(".accordion-item")) {
662                if (selected) {
663                    selected.classList.remove("active");
664                }
665                selected = event.target;
666                selected.classList.add("active");
667            }
668        }, false);
669    }
670});
671/*NB accord*/
672/*Бургер*/
673$(document).ready(function () {
674    $('.header_burger').click(function (event) {
675        $('.header_burger').show()
676        $('.header_burger,.header_menu').toggleClass('active');
677        $(this).hide()
678        $('body').toggleClass('lock');
679    });
680});
681/*Бургер*/
682/*Чат*/
683$(document).ready(function () {
684    $('.js-click-modalChat').click(function (event) {
685        $('.js-click-modalChat').addClass('active_menu');
686    });
687    $('.js-close-modalChat').click(function (event) {
688        $('.js-click-modalChat').removeClass('active_menu');
689    });
690});
691/*Чат*/
692/*Закладки Вад1*/
693$(document).ready(function () {
694    // Первый таб активный
695    $('.tabsContent > div:first-child').addClass('active');
696    // Выбираем таб
697    $('.tabsBtn > div').on('click', function () {
698        let tabsWrap = $(this).parents('.tabWrap');
699        let tabsContent = tabsWrap.find('.tabsContent > div');
700        tabsContent.removeClass('active');
701        $(tabsContent.get($(this).index())).addClass('active');
702        $('.tabsBtn > div').removeClass('active');
703        $(this).addClass('active');
704    });
705});
706/*Закладки Вад1*/
707/*Закладки*/
708$(function () {
709    var tab = $('#tabs .tabs-items > div');
710    if (tab.hasClass('active')) {
711        tab.hide();
712        $('#tabs .tabs-items > div.active').show()
713    }
714
715    // Клики по вкладкам.
716    $('#tabs .tabs-nav a').click(function () {
717        tab.hide();
718        tab.filter(this.hash).show();
719
720        $('#tabs .tabs-nav a').removeClass('active');
721        $(this).addClass('active');
722
723        return false;
724    });
725    /* $("#tabs .tabs-nav a").click(function (e) {
726         $('#tabs .tabs-nav a').removeClass('active');
727         $(this).addClass('active');
728     });*/
729
730    if (!document.location.href.match('objects') && !document.location.href.match('/map')) {
731        $('#tabs .tabs-nav a').filter(':first').addClass('active');
732        $('.search #tabs .tabs-items > div').filter(':first').show();
733        $('.MobSearch #tabs .tabs-items > div').filter(':first').show();
734    } else {
735        $($('#tabs .tabs-nav a.active').attr('href')).css('display', '');
736    }
737
738    // Клики по якорным ссылкам.
739    $('.tabs-target').click(function () {
740        $('#tabs .tabs-nav a[href=' + $(this).data('id') + ']').click();
741    });
742});
743/*Закладки*/
744
745/*Закладки2 в трех местах соединяется( Для выведения вкладки)*/
746$('.d1_radio1_hover').click(function () {
747    let input_id = $(this).attr('for');
748    $('.tabs-item2').hide(100, function () {
749        switch (input_id) {
750            case 'd1_contract':
751                $('#tabs-items2-1').show();
752                break;
753            case 'd1_payment':
754                $('#tabs-items2-2').show();
755                break;
756            case 'd1_demonstration':
757                $('#tabs-items2-3').show();
758                break;
759            case 'd1_Refusal':
760                $('#tabs-items2-4').show();
761                break;
762            case 'd1_Archive':
763                $('#tabs-items2-5').show();
764                break;
765        }
766    });
767
768    // console.log(input_id);
769});
770/*Закладки2*/
771/*Закладки3*/
772$(function () {
773    var tab = $('#tabsAT .tabs-items > div');
774    tab.hide().filter(':first').show();
775
776    // Клики по вкладкам.
777    $('#tabsAT .tabs-nav a').click(function () {
778        tab.hide();
779        tab.filter(this.hash).show();
780
781        /*$("#tabsAT .tabs-nav a").click(function (e) {
782            // Две строчки снизу были здесь
783        });*/
784        $('#tabsAT .tabs-nav a').removeClass('active');
785        $(this).addClass('active');
786
787        // return false;
788    }).filter(':first').click();
789
790    // Клики по якорным ссылкам.
791    $('.tabs-target').click(function () {
792        $('#tabsAT .tabs-nav a[href=' + $(this).data('id') + ']').click();
793    });
794});
795/*Закладки3*/
796/*Закладки4*/
797$(function () {
798    var tab = $('#tabsIP .tabs-items2 > div');
799    tab.hide().filter(':first').show();
800
801    // Клики по вкладкам.
802    $('#tabsIP .tabs-nav2 a').click(function () {
803        tab.hide();
804        tab.filter(this.hash).show();
805
806        $("#tabsIP .tabs-nav2 a").click(function (e) {
807            $('#tabsIP .tabs-nav2 a').removeClass('active');
808            $(this).addClass('active');
809        });
810
811        return false;
812    }).filter(':first').click();
813
814    // Клики по якорным ссылкам.
815    $('.tabs-target').click(function () {
816        $('#tabsIP .tabs-nav2 a[href=' + $(this).data('id') + ']').click();
817    });
818});
819/*Закладки4*/
820/*Филтер*/
821$(document).ready(function () {
822    $('.icon-menu').click(function (event) {
823        $('.icon-menu,.filter_desk').toggleClass('active');
824//        $('body').toggleClass('lock');
825    });
826});
827$(document).mouseup(function (e) {
828    let $target = $(e.target);
829
830    if (!$target.closest(".filter_desk").length
831        && !$('.flatpickr-calendar').hasClass("open")) {
832        $(".icon-menu,.filter_desk").removeClass("active");
833    }
834});
835/*Филтер*/
836
837/*select*/
838/*С поиском*/
839$(document).ready(function () {
840    $(".chosen").chosen({disable_search_threshold: 10});
841});
842/*С поиском*/
843/*без поиска*/
844
845
846/*без поиска*/
847/*select*/
848
849/*select*/
850jQuery(($) => {
851    $(document).on('click', '.select__head', function () {
852        if ($(this).hasClass('open')) {
853            $(this).removeClass('open');
854            $(this).next().fadeOut();
855        } else {
856            $(this).removeClass('open');
857            $(this).next().fadeOut();
858            $(this).addClass('open');
859            $(this).next().fadeIn();
860        }
861    });
862
863    $(document).on('click', '.select__item', function () {
864        $(this).prev().removeClass('open');
865        $(this).parent().fadeOut();
866        $(this).parent().prev().text($(this).text());
867        $(this).parent().prev().prev().val($(this).text());
868    });
869
870    $(document).click(function (e) {
871        if (!$(e.target).closest('.select').length) {
872            $('.select__head').removeClass('open');
873            $('.select__list').fadeOut();
874        }
875    });
876});
877/*select*/
878
879
880
881/*Mask only numbers*/
882$(document).ready(function () {
883    $(".only_num").keypress(function (event) {
884        event = event || window.event;
885        if (event.charCode && event.charCode != 0 && event.charCode != 46 && (event.charCode < 48 || event.charCode > 57))
886            return false;
887    });
888});
889/*Mask only numbers*/
890
891/*ДатаПикер*/
892/*Просто дата*/
893/*$(
894    '.TestYear, ' +
895    '.ProstoData'
896).flatpickr({
897    dateFormat: "d-m-Y",
898    locale: "ru"
899});*/
900/*Дата и время
901$(
902    '#StartAvito, ' +
903    '#EndAvito'
904).flatpickr({
905    enableTime: true,
906    dateFormat: "d-m-Y H:i",
907    time_24hr: true,
908    locale: "ru",
909});
910/*Дата и время без прошлого (Период даты)
911$('#DateAndTime'
912).flatpickr({
913    minDate: "today",
914    enableTime: true,
915    dateFormat: "d-m-Y H:i",
916    time_24hr: true,
917    locale: "ru",
918});
919/*Дата без прошлого (Период даты)
920$('#DateDealEnd, ' +
921    '#DataAgreement, ' +
922    '#CreationDateContract, ' +
923    '#DateDealEndRefusal, ' +
924    '#DataOfDataReturnPrepaid, ' +
925    '#DataAgreementEnd, ' +
926    '#DataOfDataCommission1, ' +
927    '#DataOfDataCommission2, ' +
928    '#DataOfDataCommission3, ' +
929    '#DataOfDataCommission4, ' +
930    '#DataOfDataCommission5, ' +
931    '#DataOfDataPrepaid, ' +
932    '#DataOfDataCommission, ' +
933    '#DataOfDataPartCommission, ' +
934    '#DataOfDataPogo, ' +
935    '#Datatatata, ' +
936    '#DataTask, ' +
937    '#DateDealEndArchive'
938).flatpickr({
939    minDate: "today",
940    dateFormat: "d-m-Y",
941    locale: "ru",
942});
943/*ДатаПикер*/
944
945
946
947
948
949$('img.img-svg').each(function () {
950    var $img = $(this);
951    var imgClass = $img.attr('class');
952    var imgURL = $img.attr('src');
953    $.get(imgURL, function (data) {
954        var $svg = $(data).find('svg');
955        if (typeof imgClass !== 'undefined') {
956            $svg = $svg.attr('class', imgClass + ' replaced-svg');
957        }
958        $svg = $svg.removeAttr('xmlns:a');
959        if (!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
960            $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
961        }
962        $img.replaceWith($svg);
963    }, 'xml');
964});
965
966/* Сворачивание */
967$(document).ready(function () {
968    $('#btn11').click(function () {
969        // .parent() selects the A tag, .next() selects the P tag
970        $("#effect1, #effect1").toggleClass("active");
971    });
972});
973$(document).ready(function () {
974    $('#btn12').click(function () {
975        // .parent() selects the A tag, .next() selects the P tag
976        $("#effect2, #effect2").toggleClass("active");
977    });
978});
979$(document).ready(function () {
980    $('#btn13').click(function () {
981        // .parent() selects the A tag, .next() selects the P tag
982        $("#effect3, #effect3").toggleClass("active");
983    });
984});
985$(document).ready(function () {
986    $('#btn14').click(function () {
987        // .parent() selects the A tag, .next() selects the P tag
988        $("#effect4, #effect4").toggleClass("active");
989    });
990});
991$(document).ready(function () {
992    $('#btn15').click(function () {
993        // .parent() selects the A tag, .next() selects the P tag
994        $("#effect5, #effect5").toggleClass("active");
995    });
996});
997$(document).ready(function () {
998    $('#btn16').click(function () {
999        // .parent() selects the A tag, .next() selects the P tag
1000        $("#effect6, #effect6").toggleClass("active");
1001    });
1002});
1003$(document).ready(function () {
1004    $('#btn17').click(function () {
1005        // .parent() selects the A tag, .next() selects the P tag
1006        $("#effect7, #effect7").toggleClass("active");
1007    });
1008});
1009$(document).ready(function () {
1010    $('#btn18').click(function () {
1011        // .parent() selects the A tag, .next() selects the P tag
1012        $("#effect8, #effect8").toggleClass("active");
1013    });
1014});
1015$(document).ready(function () {
1016    $('#btn19').click(function () {
1017        // .parent() selects the A tag, .next() selects the P tag
1018        $("#effect9, #effect9").toggleClass("active");
1019    });
1020});
1021$(document).ready(function () {
1022    $('#commOH').click(function () {
1023        // .parent() selects the A tag, .next() selects the P tag
1024        $("#commOHtoogle, #commOHtoogle").toggleClass("active");
1025    });
1026});
1027$(document).ready(function () {
1028    $('#DopOpt').click(function () {
1029        // .parent() selects the A tag, .next() selects the P tag
1030        $("#DopOpttoogle, #DopOpttoogle").toggleClass("active");
1031    });
1032});
1033$(document).ready(function () {
1034    $('#oZdanii').click(function () {
1035        // .parent() selects the A tag, .next() selects the P tag
1036        $("#oZdaniitoogle, #oZdaniitoogle").toggleClass("active");
1037    });
1038});
1039$(document).ready(function () {
1040    $('#ZemUcast').click(function () {
1041        // .parent() selects the A tag, .next() selects the P tag
1042        $("#ZemUcasttoogle, #ZemUcasttoogle").toggleClass("active");
1043    });
1044});
1045$(document).ready(function () {
1046    $('#Sklad').click(function () {
1047        // .parent() selects the A tag, .next() selects the P tag
1048        $("#Skladtoogle, #Skladtoogle").toggleClass("active");
1049    });
1050});
1051$(document).ready(function () {
1052    $('#Finans').click(function () {
1053        // .parent() selects the A tag, .next() selects the P tag
1054        $("#Finanstoogle, #Finanstoogle").toggleClass("active");
1055    });
1056});
1057$(document).ready(function () {
1058    $('#Infra').click(function () {
1059        // .parent() selects the A tag, .next() selects the P tag
1060        $("#Infratoogle, #Infratoogle").toggleClass("active");
1061    });
1062});
1063/* Сворачивание */
1064
1065/* Сворачивание моя компания*/
1066$(document).ready(function () {
1067    $('.click1').click(function (event) {
1068        $('.roll1,.prof_icon_anim1').toggleClass('active');
1069    });
1070});
1071$(document).ready(function () {
1072    $('.click2').click(function (event) {
1073        $('.roll2,.prof_icon_anim2').toggleClass('active');
1074    });
1075});
1076$(document).ready(function () {
1077    $('.click3').click(function (event) {
1078        $('.roll3,.prof_icon_anim3').toggleClass('active');
1079    });
1080});
1081
1082
1083/* Сворачивание моя компания*/
1084
1085// Автозаполнение адреса
1086$(document).ready(function () {
1087
1088    // $(document).on('keyup', '#query', async function (event) {
1089    $('#query').keydown(async function (event) {
1090        let $result = $('#address_table');
1091        $result.html('');
1092
1093        let query = $('#query').val();
1094
1095        let search = $(this).val();
1096        if ((search != '') && (search.length > 5) && (event.keyCode == 13)) {
1097            event.preventDefault();
1098
1099            const params = new URLSearchParams({
1100                query: query,
1101            })
1102            let url = `/address-suggestions?${params.toString()}`;
1103            window.answer = await fetch(url)
1104                .then(response => response.text())
1105                .then(result => {
1106                    return JSON.parse(result)['data']
1107                })
1108                .catch(error => console.log("error", error));
1109
1110            answer['suggestions'].forEach(function (entry, index) {
1111                $('#address_table').append("<tr>\n" +
1112                    "\n" +
1113                    "\t\t\t\t\t<td id='address" + index + "' class=\"search_result-name\">\n" +
1114                    "\n" +
1115                    "\t\t\t\t\t\t<a href=\"#\">" + entry['value'] + "</a>\n" +
1116                    "\n" +
1117                    "\t\t\t\t\t</td>\n" +
1118                    "\t\t\t\t</tr>");
1119            });
1120            $result.fadeIn();
1121        } else {
1122            $result.html('');
1123            $result.fadeOut(100);
1124        }
1125    })
1126
1127    $(document).on('click', function (e) {
1128        if (!$(e.target).closest('.search_box').length) {
1129            let $result = $('#address_table');
1130            $result.html('');
1131            $result.fadeOut(100);
1132        }
1133    })
1134
1135    $(document).on('click', '.search_result-name', function (e) {
1136        e.preventDefault();
1137        // console.log(window.answer);
1138        let $result = $('#address_table');
1139        let suggenstion_id = $(this).attr('id').match(/(\d+)/)['0'];
1140        $('#query').val(window.answer['suggestions'][suggenstion_id]['value'].replace(' стр ', ' с ')).trigger('change');
1141        $('#Region').val(window.answer['suggestions'][suggenstion_id]['data']['region_with_type']).trigger('change');
1142        if (window.answer['suggestions'][suggenstion_id]['data']['city_with_type'] !== window.answer['suggestions'][suggenstion_id]['data']['area_with_type']) {
1143            $('#District').val('').trigger('change');
1144        }
1145        $('#Locality').val(window.answer['suggestions'][suggenstion_id]['data']['city_with_type']).trigger('change');
1146        $('#CityDistrict').val(window.answer['suggestions'][suggenstion_id]['data']['city_district_with_type']).trigger('change');
1147        if (window.answer['suggestions'][suggenstion_id]['data']['settlement'])
1148            if (window.answer['suggestions'][suggenstion_id]['data']['street'])
1149                $('#Street').val(window.answer['suggestions'][suggenstion_id]['data']['settlement_with_type'] +
1150                    ' ' +
1151                    window.answer['suggestions'][suggenstion_id]['data']['street_with_type']).trigger('change');
1152            else
1153                $('#Street').val(window.answer['suggestions'][suggenstion_id]['data']['settlement_with_type']).trigger('change');
1154        else
1155            $('#Street').val(window.answer['suggestions'][suggenstion_id]['data']['street_with_type']).trigger('change');
1156        if (window.answer['suggestions'][suggenstion_id]['data']['block'])
1157            $('#Building').val(window.answer['suggestions'][suggenstion_id]['data']['house'] +
1158                window.answer['suggestions'][suggenstion_id]['data']['block_type'].replace(' стр ', ' с ') +
1159                window.answer['suggestions'][suggenstion_id]['data']['block'].replace(' стр ', ' с ')).trigger('change');
1160        else
1161            $('#Building').val(window.answer['suggestions'][suggenstion_id]['data']['house']).trigger('change');
1162        $('#ApartmentNumber').val(window.answer['suggestions'][suggenstion_id]['data']['flat']).trigger('change');
1163        // $('#Longitude').val(window.answer['suggestions'][suggenstion_id]['data']['geo_lon']).trigger('change');
1164        // $('#Latitude').val(window.answer['suggestions'][suggenstion_id]['data']['geo_lat']).trigger('change');
1165        $result.html('');
1166        $result.fadeOut(100);
1167        /*if (!$(e.target).closest('.search_box').length){
1168            let $result = $('#search_box-result');
1169            $result.html('');
1170            $result.fadeOut(100);
1171        }*/
1172    });
1173})
1174// Автозаполнение адреса
1175// Пагинация
1176$(document).ready(function () {
1177    $(document).on('click', '.select__item', function () {
1178        let reg_exp_pagin = /pagin=\d*&?/;
1179        let curr_url = window.location.href;
1180        let new_url;
1181        if (curr_url.search(/\/?\?/) > 0)
1182            if (curr_url.search(reg_exp_pagin) > 0)
1183                new_url = curr_url.replace(reg_exp_pagin, 'pagin=' + $(this).html() + '&');
1184            else
1185                new_url = curr_url + '&pagin=' + $(this).html();
1186        else
1187            new_url = curr_url + '?pagin=' + $(this).html();
1188        window.location = new_url;
1189    });
1190});
1191// Пагинация
1192/* Сворачивание XML*/
1193$(document).ready(function () {
1194    $('.xmla1').click(function (event) {
1195        $('.xml_accord1,.xml_accord_arrow1').toggleClass('active');
1196    });
1197});
1198$(document).ready(function () {
1199    $('.xmla2').click(function (event) {
1200        $('.xml_accord2,.xml_accord_arrow2').toggleClass('active');
1201    });
1202});
1203$(document).ready(function () {
1204    $('.xmla3').click(function (event) {
1205        $('.xml_accord3,.xml_accord_arrow3').toggleClass('active');
1206    });
1207});
1208$(document).ready(function () {
1209    $('.xmla4').click(function (event) {
1210        $('.xml_accord4,.xml_accord_arrow4').toggleClass('active');
1211    });
1212});
1213/* Сворачивание XML*/
1214
1215/* Accordion*/
1216$('.accordion').accordion({
1217    header: '> .accordion-item > .accordion-header',
1218    heightStyle: 'content',
1219    active: true,
1220    collapsible: true
1221});
1222// $('.accordion').sortable('disable');//TODO:check
1223/* Accordion*/
1224// Preloader
1225var $loading = $('#loadingDiv').hide();
1226$(document)
1227    .ajaxStart(function () {
1228        $loading.show();
1229    })
1230    .ajaxStop(function () {
1231        $loading.hide();
1232    });
1233// Preloader
1234// Metro map select
1235// let Undergrounds = [$('#Underground0').val(),$('#Underground1').val(),$('#Underground2').val()];
1236/*let Undergrounds = [];
1237$('.Underground').each(function () {
1238    Undergrounds.push($(this).val());
1239});
1240$(document).ready(function () {
1241    $('.metro-point').hide();
1242    Undergrounds.forEach(function (item, i, Undergrounds) {
1243        $('[metro-station-name="' + item + '"] > .metro-point').show();
1244    });
1245});
1246$(document).on('click', '.metro-station', function () {
1247    let station = $(this).attr('metro-station-name');
1248    let index = Undergrounds.indexOf(station);
1249    if (index >= 0) {
1250        Undergrounds.splice(index, 1);
1251        $('[metro-station-name="' + station + '"] > .metro-point').hide();
1252        $('.Underground[value="' + station + '"]').remove();
1253        // Undergrounds.push(station);
1254    } else {
1255        // Undergrounds.shift();
1256        // $('[metro-station-name="'+Undergrounds.shift()+'"] > .metro-point').hide();
1257        Undergrounds.push(station);
1258        $('#metro_list').append("<input type=\"hidden\" class=\"Underground\" name=\"Undergrounds[]\" value=\"" + station + "\">")
1259    }
1260    Undergrounds.forEach(function (item, i, Undergrounds) {
1261        $('#Underground' + i).val(item);
1262        $('[metro-station-name="' + item + '"] > .metro-point').show();
1263    });
1264});*/
1265// Metro map select
1266//
1267// Wait for the DOM to be ready
1268//Существует много способов выбрать DOM узел; здесь мы получаем форму и электронную почту
1269//поле ввода, а также элемент span, в который мы поместим сообщение об ошибке.
1270let form = $('form#form-upd');
1271let phone = $('input[name = "contact[Phone]"]');
1272let name = $('input[name = "contact[Name]"]');
1273let Status = $('select[name = "mainId[Status]"]');
1274let TotalArea = $('input[name = "TotalArea"]');
1275let LivingArea = $('input[name = "LivingArea"]');
1276let KitchenArea = $('input[name = "KitchenArea"]');
1277let error = $('.error');
1278
1279phone.on("change", function (event) {
1280    // Каждый раз, когда пользователь вводит что-либо, мы проверяем,
1281    // является ли корректным поле электронной почты.
1282    if (phone[0].checkValidity()) {
1283        // В случае появления сообщения об ошибке, если поле
1284        // является корректным, мы удаляем сообщение об ошибке.
1285        error[0].innerHTML = ""; // Сбросить содержимое сообщения
1286        error[0].className = "error"; // Сбросить визуальное состояние сообщения
1287    }
1288}, false);
1289/*Validate*/
1290// форма отправляется только раз, сколько кнопку не дрочи
1291$("body").on("submit", "#form-upd", function (event) {
1292    // event.preventDefault();
1293    // console.log(Status);
1294    // console.log(Status[0].checkValidity());
1295    // Каждый раз, когда пользователь пытается отправить данные, мы проверяем
1296    // валидность поля электронной почты.
1297    // console.log($('input[name = "contact[Phone]"]'));
1298
1299    /*    console.log(phone[0].checkValidity());
1300        console.log(name[0].checkValidity());*/
1301    if (!phone[0].checkValidity() ||
1302        !name[0].checkValidity() ||
1303        !Status[0].checkValidity() ||
1304        !TotalArea[0].checkValidity() ||
1305        !LivingArea[0].checkValidity() ||
1306        !KitchenArea[0].checkValidity() ||
1307        !checkFormValidation('Reqfield_not_checked')
1308    ) {
1309        // Если поле невалидно, отображается пользовательское
1310        // сообщение об ошибке.
1311        error.innerHTML = "I expect a phone, darling!";
1312        error.className = "error active";
1313        // И мы предотвращаем отправку формы путем отмены события
1314        event.preventDefault();
1315    } else {
1316        $(this).submit(function () {
1317            return false;
1318        });
1319        return true;
1320    }
1321});
1322// форма отправляется только раз, сколько кнопку не дрочи
1323$('#obj_cat > input').click(function () {
1324    let filter_DOM = $('.filter_box_obj');
1325    switch (($(this)).attr('id')) {
1326        case "filter_flat":
1327            filter_DOM.load('/filter_flat');
1328            break;
1329        case "filter_commerce":
1330            filter_DOM.load('/filter_commerce')
1331            break;
1332        case "filter_country":
1333            filter_DOM.load('/filter_country')
1334            break;
1335        case "filter_garage":
1336            filter_DOM.load('/filter_garage')
1337            break;
1338    }
1339})
1340//доки объектов и заявок
1341$(document).on('change', '.o_doc_file', function (e) {
1342    e.preventDefault();
1343    let field = $(this).attr('id');
1344    let formData = new FormData(this.form);
1345    formData.append("_token", $('meta[name="csrf-token"]').attr('content'));
1346    $.ajax({
1347        type: "post",
1348        url: '/up_doc',
1349        datatype: "html",
1350        enctype: 'multipart/form-data',
1351        processData: false,
1352        contentType: false,
1353        data: formData,
1354        success: function (response) {
1355            if (response) {
1356                response.forEach(function (item, i) {
1357                    $('#line_' + field).append(
1358                        '<div id="doc' + item[0] + '" class="file_card_obj flex card_doc_img">\n' +
1359                        '<a class="obj_icon_file" href="/get_doc/' + item[0] + '">\n' +
1360                        '<i class="far fa-file-image"></i>\n' +
1361                        '<div class="flex"\n' +
1362                        'style="align-self: center; padding: 0 5px;font-size: 13px;">\n' +
1363                        '<div class="obj_file_name">' + item[1].match(/\/.+$/) + '</div>\n' +
1364                        '</div>\n' +
1365                        '</a>\n' +
1366                        '<a class="doc_delete" href="/del_doc/' + item[0] + '">\n' +
1367                        '<i class="fas fa-trash"></i>\n' +
1368                        '</a>\n' +
1369                        '</div>');
1370                });
1371
1372            }
1373        }
1374    })
1375});
1376$(document).on('click', '.doc_delete', function (event) {
1377    event.preventDefault();
1378    let doc_id = $(this).attr('href').match(/(\d+)/)['0'];
1379    $.ajax({
1380        type: "get",
1381        url: $(this).attr('href'),
1382        datatype: "html",
1383        success: function (response) {
1384            if (response == 'success') {
1385                $('#doc' + doc_id).remove();
1386            }
1387        }
1388    })
1389})
1390/*Чат*/
1391
1392
1393/*Чат*/
1394/*Закладки3 XML accordion*/
1395$('.click_xml_desk').click(function () {
1396    let input_id = $(this).attr('id');
1397    $('.click_xml_desk').removeClass('xml_active');
1398    $('#' + input_id).addClass('xml_active');
1399    $('.xml_feed').hide(80, function () {
1400        switch (input_id) {
1401            case 'switch_Avito':
1402                $('#switch_Avito1').show();
1403                break;
1404            case 'switch_Cian':
1405                $('#switch_Cian1').show();
1406                break;
1407            case 'switch_Yandex':
1408                $('#switch_Yandex1').show();
1409                break;
1410            case 'switch_Domclick':
1411                $('#switch_Domclick1').show();
1412                break;
1413            case 'switch_Winner':
1414                $('#switch_Winner1').show();
1415                break;
1416            case 'switch_AFY':
1417                $('#switch_AFY1').show();
1418                break;
1419            case 'switch_N':
1420                $('#switch_N1').show();
1421                break;
1422            case 'switch_QP':
1423                $('#switch_QP1').show();
1424                break;
1425            case 'switch_ndv77':
1426                $('#switch_ndv771').show();
1427                break;
1428            case 'switch_glavbaza':
1429                $('#switch_glavbaza1').show();
1430                break;
1431            case 'switch_vseposelky':
1432                $('#switch_vseposelky1').show();
1433                break;
1434            case 'switch_kvadrat':
1435                $('#switch_kvadrat1').show();
1436                break;
1437            case 'switch_NOVOSTROY':
1438                $('#switch_NOVOSTROY1').show();
1439                break;
1440            case 'switch_rentzilla':
1441                $('#switch_rentzilla1').show();
1442                break;
1443            case 'switch_move':
1444                $('#switch_move1').show();
1445                break;
1446            case 'switch_gde':
1447                $('#switch_gde1').show();
1448                break;
1449            case 'switch_domiki':
1450                $('#switch_domiki1').show();
1451                break;
1452            case 'switch_Commercial':
1453                $('#switch_Commercial1').show();
1454                break;
1455            case 'switch_MKv':
1456                $('#switch_MKv1').show();
1457                break;
1458            case 'switch_KVM':
1459                $('#switch_KVM1').show();
1460                break;
1461            case 'switch_GED':
1462                $('#switch_GED1').show();
1463                break;
1464            case 'switch_VK':
1465                $('#switch_VK1').show();
1466                break;
1467            case 'switch_FB':
1468                $('#switch_FB1').show();
1469                break;
1470            case 'switch_Inst':
1471                $('#switch_Inst1').show();
1472                break;
1473        }
1474    });
1475
1476    // console.log(input_id);
1477});
1478/*Закладки3*/
1479
1480/* Выделение строк по ховеру */
1481$(document).on('mouseenter mouseleave', '.table_line_one', function () {
1482    $(this).toggleClass('active-row').next().toggleClass('active-row');
1483});
1484$(document).on('mouseenter mouseleave', '.table_line_two', function () {
1485    $(this).toggleClass('active-row').prev().toggleClass('active-row');
1486});
1487/* Выделение строк по ховеру */
1488
1489// $(document).on('click','#notification_tab',function (e) {
1490$(document).on('click', '.modal1BtnAT', function (e) {
1491    e.preventDefault();
1492    $('.modal1BtnAT').removeClass('active');
1493    $(this).addClass('active');
1494    $.ajax({
1495        type: "get",
1496        url: $(this).data('url'),
1497        datatype: "html",
1498        success: function (response) {
1499            $('#notification_tabs').html(response);
1500        }
1501    })
1502});
1503$(document).on('click', '.MH_trashTask.MH_delete', function (e) {
1504    e.preventDefault();
1505    $.ajax({
1506        type: "get",
1507        url: '/delete_notification/' + $(this).attr('id'),
1508        datatype: "html",
1509        success: function () {
1510            $(this).parents('.MH_Task.flex.flex_jc_sb.al_ic').remove();
1511        }
1512    })
1513});
1514
1515/* Заполнение координат */
1516$(document).ready(function () {
1517    $(document).on('paste', '#Latitude', splitCoordinates);
1518    $(document).on('paste', '#Longitude', splitCoordinates);
1519});
1520
1521function splitCoordinates(event) {
1522    let clipText;
1523    if (window.clipboardData === undefined) {
1524        clipText = event.originalEvent.clipboardData.getData('Text');
1525    } else {
1526        clipText = window.clipboardData.getData('Text'); // Получение clipboard данных в IE/Edge
1527    }
1528    clipText = clipText.split(/[,]?\s/);
1529    // Проверка что данные имеют две координаты
1530    const COORDS_COUNT = 2;
1531    if (clipText.length === COORDS_COUNT) {
1532        let latitudeValue = clipText[0];
1533        let longitudeValue = clipText[1];
1534
1535        // Заполнение полей в зависимости от того, в какое поле скопировал пользователь
1536        if ($(this).attr('id') === 'Latitude' && longitudeValue !== '') {
1537            $(this).val(latitudeValue);
1538            $('#Longitude').val(longitudeValue);
1539        } else if ($(this).attr('id') === 'Longitude' && latitudeValue !== '') {
1540            $(this).val(longitudeValue);
1541            $('#Latitude').val(latitudeValue);
1542        }
1543    }
1544}
1545
1546/* Заполнение координат */
1547
1548/* Анимация загрузки на кнопках */
1549/*$(document).ready(function () {
1550    $(document).on('click', '.load-btn', function () {
1551        $(this).addClass('loading');
1552    });
1553});*/
1554/* Анимация загрузки на кнопках */
1555
1556/* Фильтр на главной */
1557$(document).ready(function () {
1558    $(document).on('click', '.search-item', function () {
1559        $(this).toggleClass('js-opened').next().toggleClass('js-active');
1560    });
1561
1562    $(document).on('change', 'input[name="NumberOfRooms[]"]', function () {
1563        let dropdownSelect = $(this).parents('.search-item-box');
1564        checkRoomsProcess(dropdownSelect);
1565    });
1566
1567    function checkRoomsProcess(dropdownSelect) {
1568        let selectedCounts = [];
1569
1570        $(dropdownSelect).find('input[name="NumberOfRooms[]"]:checked').each(function (index, element) {
1571            selectedCounts.push($(element).next().find('.room-count').html());
1572        });
1573        if (selectedCounts.length) {
1574            let digits = selectedCounts.filter(e => e.match(/\d+/));
1575            let charactes = selectedCounts.filter(e => e.match(/\D+[^+]/));
1576            $(dropdownSelect).find('.rooms-line-interface').html(
1577                digits.join(', ') + (digits.length ? ' комн.' : '') + charactes.join(', ')
1578            );
1579        } else {
1580            $(dropdownSelect).find('.rooms-line-interface').html('Комнат');
1581        }
1582    }
1583
1584    function initCheckRooms() {
1585        $('.search-item-box').each(function (index, element) {
1586            checkRoomsProcess(element);
1587        });
1588    }
1589
1590    initCheckRooms();
1591
1592    $(document).mouseup(function (e) {
1593        let container = $('.item-dropdown');
1594
1595        if (!container.is(e.target)
1596            && container.has(e.target).length === 0
1597            && !$('.search-item').is(e.target)) {
1598            container.removeClass('js-active');
1599            $('.rooms-line-interface').removeClass('js-opened');
1600        }
1601    });
1602
1603});
1604/* Фильтр на главной */
1605
1606
1607/* Избранное */
1608/*$(document).ready(function () {
1609    $(document).on('click', '.iz1', function () {
1610        if (!$.cookie('favorite_objects')) {
1611            console.log('test');
1612            // $.cookie('favorite_objects', '', { expires: 30 })
1613        }
1614    });
1615});*/
1616/* Избранное */
1617
1618/* Отправка формы фильтра */
1619$(document).ready(function () {
1620    $(document).on('click', '.F_Submit', function (e) {
1621        $(this).parents('form').attr('action', $(this).data('url')).submit();
1622        e.preventDefault();
1623    });
1624});
1625
1626/* Отправка формы фильтра */
1627
1628/* Выделение этажей */
1629$(document).ready(function () {
1630    $(document).on('mouseenter mouseleave', '.Section_floor', function (event) {
1631        let classList = $(this).attr("class").split(/\s+/);
1632
1633        classList.forEach(function (element, index) {
1634            let match = element.match(/Floor-\d+/gi);
1635            if (match) {
1636                let activeFloor = $('.Floor-m-column .' + match[0]);
1637                let floorColumnHead = activeFloor.find('.NBC_Floors-1');
1638                let floorColumnTail = activeFloor.find('.NBC_Floors-2');
1639
1640                if (event.type === 'mouseenter') {
1641                    activeFloor.find('.NBC_LineW100').addClass('Active-row');
1642                    floorColumnHead.addClass('NBC_Active');
1643                    floorColumnTail.addClass('NBC_Active');
1644                } else {
1645                    activeFloor.find('.NBC_LineW100').removeClass('Active-row');
1646                    floorColumnHead.removeClass('NBC_Active');
1647                    floorColumnTail.removeClass('NBC_Active');
1648                }
1649            }
1650        });
1651    });
1652
1653    $(document).on('mouseenter mouseleave', '.NBC_LineW100', function (event) {
1654        let floorColumnHead = $(this).siblings('.NBC_Floors-1');
1655        let floorColumnTail = $(this).siblings('.NBC_Floors-2');
1656
1657        if (event.type === 'mouseenter') {
1658            $(this).addClass('Active-row');
1659            floorColumnHead.addClass('NBC_Active');
1660            floorColumnTail.addClass('NBC_Active');
1661        } else {
1662            $(this).removeClass('Active-row');
1663            floorColumnHead.removeClass('NBC_Active');
1664            floorColumnTail.removeClass('NBC_Active');
1665        }
1666    });
1667
1668    // $('.NBC_Entrance .Kvartirki > div');
1669});
1670/* Выделение этажей */
1671$(document).on('click','.request_butt',function(e){
1672    e.preventDefault();
1673    let exit = $('#request_form_container');
1674    let form = $(this).data('form');
1675    if (form == 2){
1676        exit = $('#request_form_2');
1677    }
1678    $.ajax({
1679        url: '/site_request_form',
1680        type: "get",
1681        datatype: "html",
1682        data: {
1683            'type':$(this).data('type'),
1684            'object_id': $(this).data('id'),
1685            'newB': $(this).data('nb'),
1686            'service': $(this).data('service'),
1687        },
1688        success: function (response) {
1689            exit.html(response);
1690        }
1691    })
1692});
1693//Заявки с сайта из header
1694$(document).on('submit', '.site_header_request,.site_request_form', function (e) {
1695    e.preventDefault();
1696    let data = $(this).serialize();
1697    let exit = $('#'+$(this).data('exit'));
1698    $.ajax({
1699        method: 'post',
1700        url: '/site_request',
1701        data,
1702        success: function () {
1703            // elem.parent('div').html('');
1704            exit.html('<div class="">\n' +
1705                '<div class="modal_header" style="font-size: 23px; font-weight: 500;"><p>Ваше сообщение отправлено.</p></div>\n' +
1706                '</div>');
1707            setTimeout(function () {
1708                $('.close-modalDI').click();
1709                $('.containerNN').removeClass('modal-openNN');
1710                $(".modalDeskInfo").removeClass("active");
1711                $('.modalDI').removeClass('active');
1712                $('body').removeClass('BodyHidden');
1713            }, 3000);
1714            // $('.modalDI .site_header_request').html('');
1715            // $('.modalDI .modal_header').html('<p>Ваше сообщение отправлено.</p>');
1716            // setTimeout(function () {
1717            //     $('.close-modalDI').click();
1718            // }, 4000);
1719        },
1720    });
1721});
1722
1723/* Липкий блок */
1724$(document).ready(function () {
1725    if ($('.sticky-element').length) {
1726        let initTop = $('.sticky-element').offset().top;
1727        $(window).scroll(function () {
1728            let offset = $(window).scrollTop() + $('.NB_menu').height() + (15) - parseInt(initTop);
1729            let containerHeight = $('.sticky-container').height() + (35) - $('.sticky-element').height() - $('.NB_menu').height();
1730            if (offset >= 0 && offset < containerHeight) {
1731                $('.sticky-element').addClass('fixed').removeClass('NB2_SlBlock');
1732            } else if (offset >= containerHeight) {
1733                $('.sticky-element').addClass('NB2_SlBlock').removeClass('fixed');
1734            } else {
1735                $('.sticky-element').removeClass('fixed').removeClass('NB2_SlBlock');
1736            }
1737        });
1738        $(window).on("resize", function(event){
1739            initTop = $('.sticky-element').offset().top;
1740        });
1741
1742        // Поднятие вкладок
1743        $('.sticky-container .tabsBtn > div').on('click', function () {
1744            $('.sticky-container .tabsBtn > div').removeClass('active');
1745            $(this).addClass('active');
1746            $([document.documentElement, document.body]).animate({
1747                scrollTop: $('.sticky-container').offset().top - $('.NB_menu').height() - 15
1748            }, 400);
1749        });
1750    }
1751});
1752/* Липкий блок */
1753
1754/* Оставляет открытыми фильтры после перезагрузки */
1755$(document).ready(function () {
1756    if (localStorage.getItem('filtersOpened') && localStorage.getItem('filtersOpened') == 'true') {
1757        $('.CatalogPage').find('.DopFilter').addClass('active');
1758    }
1759    $(document).on('click', '.CatalogPage .F_still', function () {
1760        if (localStorage.getItem('filtersOpened') == 'true') {
1761            localStorage.setItem('filtersOpened', 'false');
1762        }
1763        else {
1764            localStorage.setItem('filtersOpened', 'true');
1765        }
1766    });
1767});
1768/* Оставляет открытыми фильтры после перезагрузки */
1769/*Catalog toggle*/
1770$(document).on('click','.NBS_l1Yes',function () {
1771    $('.NBS_Card_content').addClass('NBS_GridWrap');
1772    $('.KVND_decrLink').css('display', 'flex');
1773    $('.NBS_l1Yes').addClass('active');
1774    $('.NBS_l1No').removeClass('active');
1775    localStorage.setItem('newbuildingCatalogView', 'grid');
1776});
1777
1778$(document).on('click','.NBS_l1No',function () {
1779    $('.NBS_Card_content').removeClass('NBS_GridWrap');
1780    $('.KVND_decrLink').css('display', 'none');
1781    $('.NBS_l1Yes').removeClass('active');
1782    $('.NBS_l1No').addClass('active');
1783    localStorage.setItem('newbuildingCatalogView', 'rows');
1784});
1785$(document).ready(function () {
1786    // Сохранение состояния вида каталога: плитка или строки
1787    if (window.screen.width > 480) {
1788        if (localStorage.getItem('newbuildingCatalogView') === 'grid') {
1789            $('.NBS_Card_content').addClass('NBS_GridWrap');
1790            $('.KVND_decrLink').css('display', 'flex');
1791            $('.NBS_l1Yes').addClass('active');
1792            $('.NBS_l1No').removeClass('active');
1793        } else if (localStorage.getItem('newbuildingCatalogView') === 'rows') {
1794            $('.NBS_Card_content').removeClass('NBS_GridWrap');
1795            $('.KVND_decrLink').css('display', 'none');
1796            $('.NBS_l1Yes').removeClass('active');
1797            $('.NBS_l1No').addClass('active');
1798        } else if (!localStorage.getItem('newbuildingCatalogView')) {
1799            // Установка значения по умолчанию
1800            localStorage.setItem('newbuildingCatalogView', 'grid');
1801        }
1802    }
1803});
1804/*Catalog toggle*/
1805
1806$(document).ready(function () {
1807    $(document).on('click', '.js-layout-thumbnail', function (event) {
1808        event.preventDefault();
1809        let imgSrc = $(this).find('img').attr('src');
1810        $('.modalVNB .body2').html('<img class="modal-img" src="'+imgSrc+'">');
1811    });
1812});
1813
1814/* Скролл наверх из футера */
1815$(document).ready(function () {
1816    $(document).on('click', '.js-scroll-top', function () {
1817        $("html, body").animate({ scrollTop: 0 }, "1000");
1818        return false;
1819    });
1820});
1821/* Скролл наверх из футера */
1822
1823$(document).ready(function () {
1824    $(document).on('click', '.open-filter-btn', function (event) {
1825        localStorage.setItem('filtersOpened', 'true');
1826    });
1827
1828    /*$(document).on('click', '.PrNbLinkBtn', function () {
1829        window.location = $(this).data('link');
1830    });*/
1831    let sticky = $('.sticky-header');
1832    if (sticky.length) {
1833        let stickyOffset = sticky.offset().top;
1834        let nbMenu = $('.NB_menu');
1835        let nbMenuOffset = null;
1836        if (nbMenu.length) {
1837            nbMenuOffset = nbMenu.offset().top;
1838        }
1839        $(window).scroll(function(){
1840            let scroll = $(window).scrollTop();
1841            if (nbMenu.length) {
1842                if (scroll > stickyOffset && scroll < nbMenuOffset) {
1843                    nbMenu.removeClass('savebtn_fixed');
1844                    sticky.addClass('header-fixed');
1845                } else if (scroll >= nbMenuOffset) {
1846                    nbMenu.addClass('savebtn_fixed');
1847                    sticky.removeClass('header-fixed');
1848                } else {
1849                    sticky.removeClass('header-fixed');
1850                    nbMenu.removeClass('savebtn_fixed');
1851                }
1852            } else {
1853                if (scroll > stickyOffset)
1854                    sticky.addClass('header-fixed');
1855                else
1856                    sticky.removeClass('header-fixed');
1857            }
1858        });
1859    }
1860});
1861
1862/* Мультиселект с чекбоксами */
1863$(document).ready(function () {
1864    $(document).on('click', '.seaItem1', function () {
1865        $(this).toggleClass('js-opened').next().toggleClass('js-active');
1866    });
1867});
1868$(document).ready(function () {
1869   /* $(document).on('change', '.ms-checkbox', function () {
1870        $(this).parent('label').toggleClass('active');
1871        let parent = $(this).parents('.multiselect');
1872        let results = $(parent.find('.selectBox .ms-select-results'));
1873        let checkboxes = $(parent.find('.ms-checkbox'));
1874        let resultsArray = [];
1875        checkboxes.each(function () {
1876            if ($(this).is(':checked')) {
1877                resultsArray.push($.trim($("label[for='" + $(this).attr('id') + "']").text()));
1878            }
1879        });
1880        if (resultsArray.length) {
1881            results.text(resultsArray.join(', '));
1882        } else if (results.data('placeholder')) {
1883            results.text(results.data('placeholder'));
1884        } else {
1885            results.text('Не важно');
1886        }
1887    });*/
1888
1889   /* function initCheckboxes() {
1890        $('.multiselect').each(function (index, multiselectEl) {
1891            let results = $($(multiselectEl).find('.selectBox .ms-select-results'));
1892            let checkboxes = $($(multiselectEl).find('.ms-checkbox'));
1893            let resultsArray = [];
1894            checkboxes.each(function () {
1895                if ($(this).is(':checked')) {
1896                    resultsArray.push($.trim($("label[for='" + $(this).attr('id') + "']").text()));
1897                }
1898            });
1899            if (resultsArray.length) {
1900                results.text(resultsArray.join(', '));
1901            }
1902        });
1903    }
1904
1905    initCheckboxes();*/
1906
1907    // Поиск по тексту в списке чекбоксов
1908    $(document).on('input', '.ms-search-input', function () {
1909        let input = $(this);
1910        let parent = $(this).parents('.multiselect');
1911        parent.find('.ms-checkbox-row').each(function (index, field) {
1912            let regex = new RegExp(input.val(), 'gi');
1913            if ($(field).text().match(regex)) {
1914                $(field).show();
1915            } else {
1916                $(field).hide();
1917            }
1918        });
1919    });
1920
1921    $('.radiobtn-with-uncheck label').on('click', function () {
1922        let input = $('#' + $(this).attr('for'));
1923        if (input.prop('checked')) {
1924            setTimeout(() => input.prop("checked", false).trigger("change"), 50);
1925        }
1926    });
1927});
1928
1929// /*Задержка триггер*/
1930// function delay(callback, ms) {
1931//     let timer = 0;
1932//     return function() {
1933//         let context = this, args = arguments;
1934//         clearTimeout(timer);
1935//         timer = setTimeout(function () {
1936//             callback.apply(context, args);
1937//         }, ms || 0);
1938//     };
1939// }
1940
1941/*квизы*/
1942function NewQuiz(id, howQuestion) {
1943    let tab = $(`${id} .NQ_tabs_items > div`);
1944    if (tab.hasClass('active')) {
1945        tab.hide();
1946        $(`${id} .NQ_tabs_items > div.active`).show()
1947    }
1948    // Клики по вкладкам.
1949    $(`${id} .NQ_tabs_nav a`).click(function () {
1950        tab.hide();
1951        tab.filter(this.hash).show();
1952        return false;
1953    });
1954    // Клики по якорным ссылкам.
1955    $('.NQ_tabs_target').click(function () {
1956        $(`${id} .NQ_tabs_nav a[href=' + $(this).data("id") + ']`).click();
1957    });
1958    let NumQues = $(`${id} .NW_quiz_b_l_p_title span`).text()
1959    $(`${id} .NW_quiz_b_l_p_line_percent`).css('width', 100/howQuestion*NumQues + '%')
1960    $(`${id} .NW_quiz_b_l_next`).click(function () {
1961        let tabNum = $(this).attr('href').substr($(this).attr('href').length - 1, 1);
1962        let tabNum2 = $(`${id} .NW_quiz_b_l_prev`).attr('href').substr($(`${id} .NW_quiz_b_l_prev`).attr('href').length - 1, 1);
1963        let tabNumNext = Number(tabNum) + 1;
1964        let tabNumPrev = Number(tabNum) - 1;
1965        let tabNumQues = Number(tabNum);
1966        let newAttrNext = '#tab-' + tabNumNext;
1967        let newAttrPrev = '#tab-' + tabNumPrev;
1968        $(`${id} .NW_quiz_b_l_p_title span`).text(tabNumQues);
1969        $(`${id} .NW_quiz_b_l_p_line_percent`).css('width', 100/howQuestion*tabNumQues + '%');
1970        $(`${id} .New_quiz_nav_circle:nth-child(${tabNumQues})`).addClass('active');
1971        $(`${id} .NW_quiz_b_l_prev`).addClass('NW_quiz_b_l_btn_active');
1972        if (tabNumNext <= howQuestion+1 && tabNumPrev <= howQuestion) {
1973            $(this).addClass('NW_quiz_b_l_btn_active')
1974            if (tabNumNext === howQuestion+1) {
1975                $(this).removeClass('NW_quiz_b_l_btn_active')
1976            }
1977            if (tabNumNext <= howQuestion) {
1978                $(this).attr('href', newAttrNext);
1979            }
1980            $(`${id} .NW_quiz_b_l_prev`).attr('href', newAttrPrev)
1981        }
1982    })
1983    $(`${id} .NW_quiz_b_l_prev`).click(function () {
1984        let tabNum = $(this).attr('href').substr($(this).attr('href').length - 1, 1);
1985        let tabNum2 = $(`${id} .NW_quiz_b_l_next`).attr('href').substr($(`${id} .NW_quiz_b_l_next`).attr('href').length - 1, 1);
1986        let tabNumPrev = Number(tabNum) - 1
1987        let tabNumNext = Number(tabNum) + 1
1988        let tabNumQues = Number(tabNum)
1989        let newAttrPrev = '#tab-' + tabNumPrev
1990        let newAttrNext = '#tab-' + tabNumNext
1991        $(`${id} .NW_quiz_b_l_p_title span`).text(tabNumQues)
1992        $(`${id} .NW_quiz_b_l_p_line_percent`).css('width', 100/howQuestion*tabNumQues + '%')
1993        $(`${id} .New_quiz_nav_circle:nth-child(${tabNumQues+1})`).removeClass('active');
1994        $(`${id} .NW_quiz_b_l_next`).addClass('NW_quiz_b_l_btn_active')
1995        if (tabNumPrev >= 0 && tabNumNext >= 2) {
1996            $(this).addClass('NW_quiz_b_l_btn_active')
1997            if (tabNumPrev === 0) {
1998                $(this).removeClass('NW_quiz_b_l_btn_active')
1999            }
2000            if (tabNumPrev >= 1) {
2001                $(this).attr('href', newAttrPrev);
2002            }
2003            $(`${id} .NW_quiz_b_l_next`).attr('href', newAttrNext)
2004        }
2005    })
2006}
2007NewQuiz('#nqTabs', 6);
2008NewQuiz('#nqTabs2', 8);
2009NewQuiz('#nqTabs3', 8);
2010
2011
2012$(document).mouseup(function (e) {
2013    let container = $('.SchFilSel');
2014    if (container.has(e.target).length === 0) {
2015        container.find('.SchFilSelb2_2').removeClass('open');
2016        container.find('.SchFilSelb_selectMenu').removeClass('active');
2017    }
2018});
2019
2020$('.SchFilSel').on('click', function () {
2021    $('.SchFilSelb_selectMenu').removeClass('active')
2022    $(this).find('.SchFilSelb_selectMenu').toggleClass('active');
2023    $(this).find('.SchFilSelb2_2').toggleClass('open');
2024    $(this).find('.SchFilSelb_selectMenu div').on('click', function () {
2025        $(this).parents('.SchFilSel').find('.SchFilSelb_selectMenu div.active').removeClass('active');
2026        $(this).addClass('active');
2027        let chooseText = $(this).text();
2028        $(this).parents('.SchFilSel').find('.SchFilSelb1_2').text(chooseText)
2029        $(this).parents('.SchFilSel').find('input[name="Comment[Тип заявки]"]').val(chooseText)
2030
2031    })
2032});
2033$(document).mouseup(function (e) {
2034    let container = $('.SchFilSel');
2035    if (container.has(e.target).length === 0) {
2036        container.find('.SchFilSelb2_2').removeClass('open');
2037        container.find('.SchFilSelb_selectMenu').removeClass('active');
2038    }
2039});
2040
2041$('.SchFilSelb1_input').each(function () {
2042    if ($(this).val()) {
2043        $(this).prev('.SchFilSelb1_1_label').removeClass('not_active')
2044    }
2045})
2046$(document).on('click','.SchFilSel', function() {
2047    $(this).find('.SchFilSelb1_input').focus();
2048});
2049$(document).on('focus','.SchFilSelb1_input', function () {
2050    $(this).prev('.SchFilSelb1_1_label').removeClass('not_active')
2051}).on('focusout', '.SchFilSelb1_input', function () {
2052    if (!$(this).val()) {
2053        $(this).prev('.SchFilSelb1_1_label').addClass('not_active')
2054    }
2055});
2056
2057function getClientLocation() {
2058    return $.ajax({
2059        url: '/geolocation',
2060        type: 'get',
2061        dataType: 'json'
2062    }).then(function(response) {
2063        return response['city'];
2064    });
2065}
2066
2067$(document).ready(async function () {
2068    $('.chosen_city').on('mouseenter', function () {
2069        $('.chosen_city_menu').addClass('active')
2070    })
2071    $(document).mouseup(function (e) {
2072        let container = $('.chosen_city');
2073        if (container.has(e.target).length === 0) {
2074            container.find('.chosen_city_menu').removeClass('active');
2075        }
2076    });
2077
2078    let office;
2079
2080    function cityChooseTimeout() {
2081        setTimeout(function () {
2082            window.location.href = $('.chosen_city_yes_or_no .chosen_city_y_o_n_btn_yes').attr('href');
2083        }, 4000);
2084    }
2085
2086    if (crm_offices.length >=1) {
2087        if (sessionStorage.getItem('chosen_office')) {
2088            office = crm_offices.find(x => x.id == sessionStorage.getItem('chosen_office'));
2089            if (!office) {
2090                office = crm_offices[0];
2091                sessionStorage.setItem('chosen_office', office.id);
2092            } else {
2093                if (office.city) {
2094                    $('.chosen_city_text').text(office.city)
2095                } else {
2096                    $('.chosen_city_text').text(office.name)
2097                }
2098                if (office.phone) {
2099                    $('.chosen_phone_text').text(office.phone)
2100                    $('.chosen_phone_text').parent().attr('href', 'tel:' + office.phone)
2101                } else {
2102                    $('.chosen_phone_text').parent().remove()
2103                }
2104                $('.office_element').hide();
2105                $('.indexOfficeGr').removeClass('active');
2106                $(`.office_element[data-office="${office.id}"]`).show();
2107                $(`.indexOfficeGr[data-office="${office.id}"]`).addClass('active');
2108                $(`.office_locality_input[data-office="${office.id}"]`).trigger('click')
2109                $(`.office_filter_input_s + .multiselect`).multiSelectChange(office.id);
2110                $('.office_input').val(office.id);
2111            }
2112        } else {
2113            let rescont = await getClientLocation();
2114            if (rescont) {
2115                let office = crm_offices.find(x => x.city == `${rescont}`);
2116                if (!office) {
2117                    office = crm_offices[0];
2118                    sessionStorage.setItem('chosen_office', office.id);
2119                    $('.chosen_city_yes_or_no_wrap').show()
2120                    cityChooseTimeout();
2121                    $('.office_element').hide();
2122                    $('.indexOfficeGr').removeClass('active');
2123                    $(`.office_element[data-office="${office.id}"]`).show();
2124                    $(`.indexOfficeGr[data-office="${office.id}"]`).addClass('active');
2125                    $(`.office_locality_input[data-office="${office.id}"]`).trigger('click')
2126                    $(`.office_filter_input_s + .multiselect`).multiSelectChange(office.id);
2127                    $('.office_input').val(office.id);
2128                } else {
2129                    let officeUrl = `/${office.subdomain}${window.location.pathname}${window.location.search}`;
2130                    if (office.city) {
2131                        $('.chosen_city_text').text(office.city)
2132                        $('.chosen_city_yes_or_no_wrap').show()
2133                        cityChooseTimeout();
2134                    } else {
2135                        $('.chosen_city_text').text(office.name)
2136                        $('.chosen_city_yes_or_no_wrap').show()
2137                        cityChooseTimeout();
2138                    }
2139                    $('.chosen_city_y_o_n_btn_yes').attr('href', officeUrl)
2140                    sessionStorage.setItem('chosen_office', office.id);
2141                    $('.office_element').hide();
2142                    $('.indexOfficeGr').removeClass('active');
2143                    $(`.office_element[data-office="${office.id}"]`).show();
2144                    $(`.indexOfficeGr[data-office="${office.id}"]`).addClass('active');
2145                    $(`.office_locality_input[data-office="${office.id}"]`).trigger('click')
2146                    $(`.office_filter_input_s + .multiselect`).multiSelectChange(office.id);
2147                    $('.office_input').val(office.id);
2148                }
2149
2150                if (office && window.getIndexExclusives) {
2151                    getIndexExclusives(office.id)
2152                }
2153                if (office && window.getIndexNYSale) {
2154                    getIndexNYSale(office.id)
2155                }
2156                if (office && window.getNewBuildFlats) {
2157                    getNewBuildFlats(office.id);
2158                }
2159
2160                $(document).trigger("office:get_location", [office.id]);
2161            } else {
2162                office = crm_offices.find(x => x.id == sessionStorage.getItem('chosen_office'));
2163                if (!office) {
2164                    office = crm_offices[0];
2165                    $(`.indexOfficeGr[data-office="${office.id}"]`).addClass('active');
2166                    sessionStorage.setItem('chosen_office', office.id);
2167                } else {
2168                    if (office.city) {
2169                        $('.chosen_city_text').text(office.city)
2170                        $('.chosen_city_yes_or_no_wrap').show()
2171                        cityChooseTimeout();
2172                    } else {
2173                        $('.chosen_city_text').text(office.name)
2174                        $('.chosen_city_yes_or_no_wrap').show()
2175                        cityChooseTimeout();
2176                    }
2177                    $('.office_element').hide();
2178                    $('.indexOfficeGr').removeClass('active');
2179                    $(`.office_element[data-office="${office.id}"]`).show();
2180                    $(`.indexOfficeGr[data-office="${office.id}"]`).addClass('active');
2181                    $(`.office_locality_input[data-office="${office.id}"]`).trigger('click')
2182                    $(`.office_filter_input_s + .multiselect`).multiSelectChange(office.id);
2183                    $('.office_input').val(office.id);
2184                }
2185            }
2186            // office = crm_offices[0];
2187            // sessionStorage.setItem('chosen_office', office.id);
2188            $('.chosen_city_yes_or_no_wrap').show()
2189            cityChooseTimeout();
2190        }
2191
2192        /*crm_offices объявляется в head*/
2193        $('.chosen_city_menu div, .indexOfficeGr').on('click', function (e) {
2194            let office = crm_offices.find(x => x.id == $(this).data('office'));
2195            if (office) {
2196                sessionStorage.setItem('chosen_office', office.id);
2197                $(document).trigger('office:changed', [office]);
2198                $('.office_element').hide();
2199                $('.indexOfficeGr').removeClass('active');
2200                $(`.office_element[data-office="${office.id}"]`).show();
2201                $(`.indexOfficeGr[data-office="${office.id}"]`).addClass('active');
2202                $(`.office_locality_input[data-office="${office.id}"]`).trigger('click')
2203                if (office.city) {
2204                    $('.chosen_city_text').text(office.city);
2205                } else {
2206                    $('.chosen_city_text').text(office.name);
2207                }
2208                // $(`.office_phone`).attr('href',`tel:${office.phone}`);
2209                // $(`.office_phone div`).html(`${office.phone}`);
2210                // $('office_phone .phone').mask('+9(999)999-99-99');
2211                $('.modalChosenCity_close ').trigger('click')
2212                $(`.office_filter_input + .multiselect`).multiSelectChange(office.id);
2213                $('.office_input').val(office.id);
2214            }
2215            if (office && window.getIndexExclusives) {
2216                getIndexExclusives(office.id)
2217            }
2218            if (office && window.getIndexNYSale) {
2219                getIndexNYSale(office.id)
2220            }
2221            if (office && window.getNewBuildFlats) {
2222                getNewBuildFlats(office.id);
2223            }
2224
2225            if (office && window.getNewbuildTable) {
2226                getNewbuildTable()
2227            }
2228            if (office && window.getObjects) {
2229                $('#obj_filter').trigger('submit');
2230            }
2231        })
2232        $('.chosen_city_y_o_n_btn_no').on('click', function () {
2233            $('.chosen_city_yes_or_no_wrap').hide();
2234            $('.containerChosenCity').addClass('active');
2235            $('.modalChosenCity').addClass('active');
2236        })
2237        $('.chosen_city_y_o_n_btn_yes').on('click', function () {
2238            $('.chosen_city_yes_or_no_wrap').hide();
2239        })
2240        $('.modalChosenCity_close').on('click', function () {
2241            $('.containerChosenCity').removeClass('active');
2242            $('.modalChosenCity').removeClass('active');
2243        })
2244
2245        if (office && window.getIndexExclusives) {
2246            getIndexExclusives(office.id)
2247        }
2248        if (office && window.getIndexNYSale) {
2249            getIndexNYSale(office.id)
2250        }
2251        if (office && window.getNewBuildFlats) {
2252            getNewBuildFlats(office.id);
2253        }
2254    }
2255})
2256
2257
2258function addToFavorites($heartElement) {
2259
2260    $heartElement.addClass('clicked');
2261
2262    let $flyingHeart = $heartElement.clone();
2263    $flyingHeart.find('svg').addClass('favorite_object');
2264    $flyingHeart.addClass('fly-heart');
2265    $('body').append($flyingHeart);
2266
2267    let heartOffset = $heartElement.offset();
2268    let counterOffset = $('#favourite_counter').offset();
2269
2270    let translateX = counterOffset.left - heartOffset.left;
2271    let translateY = -700;
2272
2273    $flyingHeart.css({
2274        left: heartOffset.left,
2275        top: heartOffset.top,
2276        position: 'absolute',
2277        'z-index': '999999'
2278    }).animate({
2279        top: `+=${translateY}px`,
2280        left: `+=${translateX}px`,
2281        opacity: 0
2282    }, 1500);
2283}
2284
2285let swiperRio2 = new Swiper(".rio_swiper2", {
2286    loop: false,
2287    mousewheel: false,
2288    allowTouchMove: false,
2289    breakpoints: {
2290        650: {
2291            spaceBetween: 0,
2292        },
2293        // when window width is >= 650
2294        200: {
2295            spaceBetween: 5,
2296        }
2297    },
2298});
2299let swiperRio = new Swiper(".rio_swiper", {
2300    loop: false,
2301    spaceBetween: 0,
2302    effect: 'fade',
2303    navigation: {
2304        nextEl: ".rio_swiper-button-next",
2305        prevEl: ".rio_swiper-button-prev",
2306    },
2307    thumbs: {
2308        swiper: swiperRio2,
2309    },
2310});
2311if ($(window).width() < 600) {
2312    let firstHeight = $('.swiper-slide-active').innerHeight()
2313    $('.rio_swiper2').css('height', firstHeight + 'px')
2314    swiperRio2.on('slideChange', function () {
2315        $('.rio_swiper2').css('height', 'auto');
2316        let slideHeight = $('.RIO_Sl_txt[data-index="' + swiperRio.realIndex + '"]').innerHeight();
2317        $('.rio_swiper2').animate(
2318            {height: slideHeight + 'px'}, 0)
2319    });
2320}
2321// анимация летающих созвездий
2322/*$(document).ready(function () {
2323    if ($(window).width() > 600) {
2324        const canvas = document.getElementById('sky');
2325        const ctx = canvas.getContext('2d');
2326        let W = canvas.width = window.innerWidth;
2327        let H = canvas.height = window.innerHeight;
2328
2329        const STAR_COUNT = 350;
2330        const CONNECT_DIST = 160;
2331        const VISION_RADIUS = 200;
2332        const stars = [];
2333        let mouse = {x: -9999, y: -9999, visible: false};
2334        let ready = false; // блок реакции курсора
2335
2336// ---------- Создание звёзд ----------
2337        function generateStars() {
2338            stars.length = 0;
2339            for (let i = 0; i < STAR_COUNT; i++) {
2340                const bx = Math.random() * W;
2341                const by = Math.random() * H;
2342                stars.push({
2343                    baseX: bx,
2344                    baseY: by,
2345                    x: bx + (Math.random() - 0.5) * 30, // стартовая дрожь
2346                    y: by + (Math.random() - 0.5) * 30,
2347                    r: Math.random() * 2 + 1,
2348                    alpha: 0,
2349                    targetX: bx,
2350                    targetY: by,
2351                    moveTimer: 0,
2352                    moveDelay: Math.random() * 100 + i * 2
2353                });
2354            }
2355        }
2356
2357        generateStars();
2358
2359// ---------- Обновление ----------
2360        function updateStars() {
2361            for (let s of stars) {
2362                // выход на базовые позиции
2363                s.x += (s.targetX - s.x) * 0.05;
2364                s.y += (s.targetY - s.y) * 0.05;
2365                // асинхронные микро-движения
2366                s.moveTimer++;
2367                if (s.moveTimer > s.moveDelay) {
2368                    s.targetX = s.baseX + (Math.random() - 0.5) * 64;
2369                    s.targetY = s.baseY + (Math.random() - 0.5) * 64;
2370                    s.moveDelay = Math.random() * 100 + 50;
2371                    s.moveTimer = 0;
2372                }
2373                // яркость только если сцена готова
2374                if (ready && mouse.visible) {
2375                    const dx = s.x - mouse.x;
2376                    const dy = s.y - mouse.y;
2377                    const dist = Math.sqrt(dx * dx + dy * dy);
2378                    const ta = dist < VISION_RADIUS ? (1 - dist / VISION_RADIUS) : 0;
2379                    s.alpha += (ta - s.alpha) * 0.4;
2380                } else {
2381                    s.alpha += (0 - s.alpha) * 0.08;
2382                }
2383            }
2384        }
2385// ---------- Рисование ----------
2386        function drawStars() {
2387            ctx.clearRect(0, 0, W, H);
2388            ctx.lineWidth = 1;
2389            ctx.shadowColor = '#fff';
2390            ctx.shadowBlur = 10;
2391
2392            for (let i = 0; i < stars.length; i++) {
2393                const a = stars[i];
2394                if (a.alpha < 0.02) continue;
2395                for (let j = i + 1; j < stars.length; j++) {
2396                    const b = stars[j];
2397                    if (b.alpha < 0.02) continue;
2398                    const dx = a.x - b.x;
2399                    const dy = a.y - b.y;
2400                    const dist = Math.sqrt(dx * dx + dy * dy);
2401                    if (dist < CONNECT_DIST) {
2402                        const op = Math.min(a.alpha, b.alpha) * (1 - dist / CONNECT_DIST);
2403                        if (op > 0.03) {
2404                            ctx.strokeStyle = `rgba(255,255,255,${op})`;
2405                            ctx.beginPath();
2406                            ctx.moveTo(a.x, a.y);
2407                            ctx.lineTo(b.x, b.y);
2408                            ctx.stroke();
2409                        }
2410                    }
2411                }
2412            }
2413
2414            for (let s of stars) {
2415                if (s.alpha > 0.01) {
2416                    ctx.beginPath();
2417                    ctx.arc(s.x, s.y, s.r, 0, Math.PI * 3);
2418                    ctx.fillStyle = `rgba(255,255,255,${s.alpha})`;
2419                    ctx.fill();
2420                }
2421            }
2422        }
2423
2424// ---------- Анимация ----------
2425        function animate() {
2426            updateStars();
2427            drawStars();
2428            requestAnimationFrame(animate);
2429        }
2430        animate();
2431// ---------- Управление курсором ----------
2432        document.addEventListener('mousemove', e => {
2433            if (!ready) return; // до готовности игнорируем
2434            mouse.x = e.clientX;
2435            mouse.y = e.clientY;
2436            mouse.visible = true;
2437        });
2438        document.addEventListener('mouseleave', () => mouse.visible = false);
2439        window.addEventListener('resize', () => {
2440            W = canvas.width = window.innerWidth;
2441            H = canvas.height = window.innerHeight;
2442            generateStars();
2443        });
2444// ---------- Отложенная активация реакции ----------
2445        setTimeout(() => {
2446            ready = true;
2447        }, 500); // включаем через 0.5 секунды
2448    }
2449})*/
2450
2451/*Mask*/
2452$(document).ready(function () {
2453    $('.seriaP').mask('00 00');
2454    $('.nomerP').mask('000 000');
2455    $('.mycoordinates').mask('99.999999');
2456    $('.percent').mask('000');
2457    $('.xmldate').mask('00:00');
2458    $('.xmldateold1').mask('00/00/0000/00:00');
2459    $('.mydata').mask('00/00/0000');
2460    $('.birth_date').mask('00-00-0000');
2461    $('.mydatammgggg').mask('00-00-0000');
2462    $('.time').mask('00:00:00');
2463    $('.date_time').mask('00-00-0000 00:00:00');
2464    $('.email').mask('[email protected]');
2465    /*
2466        $('.phone').on('input', function () {
2467            let val = $(this).val();
2468            if (val[0] == 8 || val[0] == 7) {
2469                $(this).val('7(' + val.slice(1));
2470            }
2471        });*/
2472    $('.phone').mask('+9(999)999-99-99');
2473
2474    $('.phone_with_ddd').mask('(00) 0000-0000');
2475    $('.phone_us').mask('(000) 000-0000');
2476    $('.mixed').mask('AAA 000-S0S');
2477    $('.cpf').mask('000.000.000-00', {reverse: true});
2478    $('.money').mask('000 000 000 000 000', {reverse: true});
2479    $('.money2').mask('000 000 000 000 000', {reverse: true});
2480    $('.moneykvm').mask('000 000 000 000 000.00', {reverse: true});
2481});
2482/*Mask*/
2483
2484// cookies
2485$(document).ready(function() {
2486    // Проверяем, не соглашался ли уже пользователь с cookies
2487    if (!getCookie('cookies_accepted')) {
2488        // Показываем уведомление с задержкой 1 секунду
2489        setTimeout(function() {
2490            $('#cookie-notification').fadeIn(300);
2491        }, 1000);
2492    }
2493
2494    // Обработчик принятия cookies
2495    $('#cookie-accept').click(function() {
2496        setCookie('cookies_accepted', 'true', 365); // Сохраняем на год
2497        $('#cookie-notification').fadeOut(300);
2498        // Здесь можно добавить код для активации cookies
2499    });
2500
2501    // Обработчик отклонения cookies
2502    $('#cookie-decline').click(function() {
2503        setCookie('cookies_accepted', 'false', 30); // Сохраняем на 30 дней
2504        $('#cookie-notification').fadeOut(300);
2505        // Здесь можно добавить код для деактивации cookies
2506    });
2507
2508    // Функция установки cookie
2509    function setCookie(name, value, days) {
2510        let expires = "";
2511        if (days) {
2512            const date = new Date();
2513            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
2514            expires = "; expires=" + date.toUTCString();
2515        }
2516        document.cookie = name + "=" + (value || "") + expires + "; path=/; SameSite=Lax";
2517    }
2518
2519    // Функция получения cookie
2520    function getCookie(name) {
2521        const nameEQ = name + "=";
2522        const ca = document.cookie.split(';');
2523        for(let i = 0; i < ca.length; i++) {
2524            let c = ca[i];
2525            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
2526            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
2527        }
2528        return null;
2529    }
2530});

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.