PageSourceSearch

https://transhub24.com/local/templates/transhub/js/common.js

js transhub24.com collected 2026-10-07 04:06:48 UTC 68,961 bytes, 1,694 lines download raw bytes

1// сообщение в форме
2function showMessage($form, message = '', selector = '.form-field-error') {
3    $form.find(selector).text(message);
4}
5
6// ajax-отправка формы
7function formSend($form, callback) {
8    showMessage($form);
9
10    if ($form.valid()) {
11        $.ajax({
12            url: '/local/ajax/',
13            data: $form.serialize(),
14            dataType: 'json',
15            type: 'post',
16            success: function (data) {
17                if (data['status'] === 'ok') {
18                    if (callback) {
19                        callback(data);
20                    } else {
21                        window.location = '/personal/';
22                    }
23                } else if (data['status'] === 'newuser') {
24                    $('#verifiedRegister').addClass("fadeIn active");
25                    //window.location = '/personal/?newuser=true';
26                } else {
27                    showMessage($form, data['message']);
28                }
29            },
30            error: function (jqXHR, textStatus, errorThrown) {
31                showMessage($form, 'Ошибка при отправке данных');
32            }
33        });
34    }
35}
36
37
38// поменять значение инпутов
39function swapInputValue(element, $name1, $name2) {
40    var
41        $row = $(element).closest('.row'),
42        value = $row.find($name1).val();
43
44    $row.find($name1).val($row.find($name2).val());
45    $row.find($name2).val(value);
46
47}
48
49// поменять checked инпутов
50function swapInputChecked(element, $name1, $name2) {
51    var
52        $row = $(element).closest('.row'),
53        value = $row.find($name1).prop('checked');
54
55    $row.find($name1).prop('checked', $row.find($name2).prop('checked'));
56    $row.find($name2).prop('checked', value);
57
58}
59
60// размер файла
61function fileSize(size) {
62    var i = Math.floor(Math.log(size) / Math.log(1024));
63    return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
64}
65
66// Сериализует поля и поля с файлами для jquery ajax
67$.fn.serializeFiles = function () {
68    var
69        $this = $(this),
70        formData = new FormData(),
71        params = $this.serializeArray();
72
73    $.each($this.find("input[type='file']"), function (i, item) {
74        $.each($(item)[0].files, function (i, file) {
75            formData.append(item.name, file);
76        });
77    });
78
79    $.each(params, function (i, item) {
80        formData.append(item.name, item.value);
81    });
82
83    return formData;
84};
85
86
87$(function () {
88
89//	$('.checkselect').checkselect();
90
91    $(document).on('click','#verifiedRegister',function (){
92        window.location = '/personal/?newuser=true';
93    })
94
95    // авторизация
96    $('#form-auth').submit(function () {
97        formSend($(this));
98
99        return false;
100    });
101
102    $('.form-auth-main').submit(function () {
103        formSend($(this));
104
105        return false;
106    });
107
108    $('#recover-password-form').submit(function () {
109        var
110            $form = $(this);
111
112        showMessage($form);
113
114        if ($form.valid()) {
115            $.ajax({
116                url: '/local/ajax/',
117                data: $form.serialize(),
118                dataType: 'json',
119                type: 'post',
120                success: function (data) {
121                    if (data['status'] === 'ok') {
122                        $form.addClass('submit-success');
123                        $form.trigger('reset');
124                    } else {
125                        showMessage($form, data['message']);
126                    }
127                },
128                error: function (jqXHR, textStatus, errorThrown) {
129                    showMessage($form, 'Ошибка при отправке данных');
130                }
131            });
132
133            return false;
134        }
135    });
136
137    // переключалка тарифов при регистрации
138    $('#org_tariff').change(function () {
139        var $option = $(this).children('option:selected');
140
141        $('#tariff_id').val($option.val());
142        $('#tariff_price').text($option.data('price'));
143        $('#tariff_name').text($option.text());
144        $('#tariff_description').html($option.data('description'));
145    });
146
147    $(document).ready(function () {
148        var $option = $('#org_tariff').children('option:selected');
149        $('#tariff_price').addClass('tariff_price_red');
150    });
151
152    $('#org_type').change(function () {
153        $('#type_id').val($option.val());
154    });
155
156    $('#from-register-leasing').submit(function () {
157        formSend($(this));
158
159        return false;
160    });
161
162    // регистрация Перевозчик
163    $('#form-register-driver').submit(function () {
164        formSend($(this));
165
166        return false;
167    });
168
169
170    // регистрация Грузоотправитель
171    $('#form-register-client').submit(function () {
172        formSend($(this));
173
174        return false;
175    });
176
177    // переключатель типа физ/юр
178    $('#form-register-client').on('click', '.nav-link', function () {
179        $('#form-register-client #type').val($(this).data('target') === '#reg_fiz_client' ? '1' : '2');
180    });
181
182
183    // регистрация Продавец
184    $('#form-register-seller').submit(function () {
185        formSend($(this));
186
187        return false;
188    });
189
190    // переключатель типа физ/юр
191    $('#form-register-seller').on('click', '.nav-link', function () {
192        $('#form-register-seller #type').val($(this).data('target') === '#reg_fiz_client' ? '1' : '2');
193    });
194
195
196    // регистрация Лизинг
197    $('#form-register-leasing').submit(function () {
198        formSend($(this));
199
200        return false;
201    });
202
203    $(document).on('click','#delete_user .button_yes', function (e) {
204        $.ajax({
205            type: 'POST',
206            url: '/local/ajax/deleteAccount.php',
207            success: function (data) {
208                $('#delete_user').removeClass("fadeIn active");
209                $('#delete_user_success').addClass("fadeIn active");
210            }
211        })
212    });
213
214
215    //Статьи "Загрузить ещё"
216    $(document).on('click', '.load_more_articles', function () {
217        var targetContainer = $('.articles-block__articles-list'),          //  Контейнер, в котором хранятся элементы
218            url = $('.load_more_articles').attr('data-url');    //  URL, из которого будем брать элементы
219        if (url !== undefined) {
220            $.ajax({
221                type: 'GET',
222                url: url,
223                dataType: 'html',
224                success: function (data) {
225                    //  Удаляем старую навигацию
226                    $('.load_more_articles').remove();
227                    $('.pagination').remove();
228                    var elements = $(data).find('.articles-block__item-wrapper'),  //  Ищем элементы
229                        paginationbutton = $(data).find('.load_more_articles');//  Ищем навигацию
230                    paginationchain = $(data).find('.pagination');//  Ищем навигацию
231                    targetContainer.append(elements);   //  Добавляем посты в конец контейнера
232                    targetContainer.append(paginationbutton); //  добавляем навигацию следом
233                    targetContainer.append(paginationchain); //  добавляем навигацию следом
234                }
235            })
236        }
237    });
238
239    //Показать ещё "Объявления"
240    $(document).on('click', '.load_more_adv', function () {
241        var targetContainer = $('.adv-block__adv-list'),          //  Контейнер, в котором хранятся элементы
242            url = $('.load_more_adv').attr('data-url');    //  URL, из которого будем брать элементы
243        if (url !== undefined) {
244            $.ajax({
245                type: 'GET',
246                url: url,
247                dataType: 'html',
248                success: function (data) {
249                    //  Удаляем старую навигацию
250                    $('.load_more_adv').remove();
251                    $('.pagination').remove();
252                    var elements = $(data).find('.adv-block__item-wrapper'),  //  Ищем элементы
253                        paginationbutton = $(data).find('.load_more_adv');//  Ищем навигацию
254                    paginationchain = $(data).find('.pagination');//  Ищем навигацию
255                    targetContainer.append(elements);   //  Добавляем посты в конец контейнера
256                    targetContainer.append(paginationbutton); //  добавляем навигацию следом
257                    targetContainer.append(paginationchain); //  добавляем навигацию следом
258                }
259            })
260        }
261    });
262
263    //Лизинговые компании "Загрузить ещё"
264    $(document).on('click', '.load_more_leasing_companies', function () {
265        var targetContainer = $('.leasing_company_list'),          //  Контейнер, в котором хранятся элементы
266            url = $('.load_more_leasing_companies').attr('data-url');    //  URL, из которого будем брать элементы
267        if (url !== undefined) {
268            $.ajax({
269                type: 'GET',
270                url: url,
271                dataType: 'html',
272                success: function (data) {
273                    //  Удаляем старую навигацию
274                    $('.load_more_leasing_companies').remove();
275                    $('.pagination').remove();
276                    var elements = $(data).find('.company_wraper'),  //  Ищем элементы
277                        paginationbutton = $(data).find('.load_leasing_companies');//  Ищем навигацию
278                    paginationchain = $(data).find('.pagination');//  Ищем навигацию
279                    targetContainer.append(elements);   //  Добавляем посты в конец контейнера
280                    $('#find_contractor_list').after(paginationbutton); //  добавляем навигацию следом
281                    $('#find_contractor_list').after(paginationchain); //  добавляем навигацию следом
282                }
283            })
284        }
285    });
286
287    //Каталог перевозчиков "Загрузить ещё"
288    $(document).on('click', '.load_more_drivers', function () {
289        var targetContainer = $('.drivers_list'),          //  Контейнер, в котором хранятся элементы
290            url = $('.load_more_drivers').attr('data-url');    //  URL, из которого будем брать элементы
291        if (url !== undefined) {
292            $.ajax({
293                type: 'GET',
294                url: url,
295                dataType: 'html',
296                success: function (data) {
297                    //  Удаляем старую навигацию
298                    $('.load_more_drivers').remove();
299                    $('.pagination').remove();
300                    var elements = $(data).find('.drivers_item'),  //  Ищем элементы
301                        paginationbutton = $(data).find('.load_more_drivers');//  Ищем навигацию
302                    paginationchain = $(data).find('.pagination');//  Ищем навигацию
303                    targetContainer.append(elements);   //  Добавляем посты в конец контейнера
304                    $('#find_contractor_list').after(paginationbutton); //  добавляем навигацию следом
305                    $('#find_contractor_list').after(paginationchain); //  добавляем навигацию следом
306                    //Реинициализация select-звезд
307                    $('.rating-block').barrating({
308                        theme: 'css-stars',
309                        allowEmpty: true,
310                        readonly: true
311                    });
312
313                    $('.rate-select').barrating({
314                        theme: 'css-stars',
315                        allowEmpty: true,
316                        onSelect: function (value, text, event) {
317                            if (typeof (event) !== 'undefined') {
318                                if ($(event.target).parents('.form-validate').length > 0) {
319                                    $(event.target).parents('.br-wrapper').find('select').valid();
320                                }
321                            }
322                        }
323                    });
324                }
325            })
326        }
327    });
328
329    //Каталог грузоотправителей "Загрузить ещё"
330    $(document).on('click', '.load_more_shippers', function () {
331        var targetContainer = $('.shippers_list'),          //  Контейнер, в котором хранятся элементы
332            url = $('.load_more_shippers').attr('data-url');    //  URL, из которого будем брать элементы
333        if (url !== undefined) {
334            $.ajax({
335                type: 'GET',
336                url: url,
337                dataType: 'html',
338                success: function (data) {
339                    //  Удаляем старую навигацию
340                    $('.load_more_shippers').remove();
341                    $('.pagination').remove();
342                    var elements = $(data).find('.shippers_item'),  //  Ищем элементы
343                        paginationbutton = $(data).find('.load_more_shippers');//  Ищем навигацию
344                    paginationchain = $(data).find('.pagination');//  Ищем навигацию
345                    targetContainer.append(elements);   //  Добавляем посты в конец контейнера
346                    $('#find_contractor_list').after(paginationbutton); //  добавляем навигацию следом
347                    $('#find_contractor_list').after(paginationchain); //  добавляем навигацию следом
348                    //Реинициализация select-звезд
349                    $('.rating-block').barrating({
350                        theme: 'css-stars',
351                        allowEmpty: true,
352                        readonly: true
353                    });
354
355                    $('.rate-select').barrating({
356                        theme: 'css-stars',
357                        allowEmpty: true,
358                        onSelect: function (value, text, event) {
359                            if (typeof (event) !== 'undefined') {
360                                if ($(event.target).parents('.form-validate').length > 0) {
361                                    $(event.target).parents('.br-wrapper').find('select').valid();
362                                }
363                            }
364                        }
365                    });
366                }
367            })
368        }
369    });
370
371    //Отзывы "Загрузить ещё"
372    $(document).on('click', '.load_more_review', function () {
373        var targetContainer = $('.load_more_review_wraper'),          //  Контейнер, в котором хранятся элементы
374            url = $('.load_more_review').attr('data-url');    //  URL, из которого будем брать элементы
375        if (url !== undefined) {
376            $.ajax({
377                type: 'GET',
378                url: url,
379                dataType: 'html',
380                success: function (data) {
381                    //  Удаляем старую навигацию
382                    $('.load_more_review').remove();
383                    $('.pagination').remove();
384                    var elements = $(data).find('.load_more_review_item'),  //  Ищем элементы
385                        paginationbutton = $(data).find('.load_more_review');//  Ищем навигацию
386                    paginationchain = $(data).find('.pagination');//  Ищем навигацию
387                    targetContainer.append(elements);   //  Добавляем посты в конец контейнера
388                    $('.load_more_review_wraper').after(paginationbutton); //  добавляем навигацию следом
389                    $('.load_more_review_wraper').after(paginationchain); //  добавляем навигацию следом
390                    $('.rating-block').barrating({
391                        theme: 'css-stars',
392                        allowEmpty: true,
393                        readonly: true
394                    });
395                }
396            })
397        }
398    });
399
400    //Подгрузка регионов в easy Autoselect на странице Справочники Базы знаний
401    if ((window.location.href).indexOf('/knowledge/reference/') != '-1') {
402        BX.ajax({
403            url: '/local/ajax/getRegionForAutoselect.php',
404            method: 'POST',
405            data: {
406                'sectionId': $(".autocomplete-select").data('sectionid')
407            },
408            dataType: 'json',
409            onsuccess: function (response) {
410                $(".autocomplete-select").easyAutocomplete({
411                    data: response,
412                    getValue: "name",
413                    list: {match: {enabled: !0}},
414                    theme: "square"
415                })
416            },
417            onfailure: function () {
418            }
419        });
420    }
421
422    $(document).on('change', '.autocomplete-select', function () {
423        $(".railways-block__filter-form").submit();
424    });
425    ymaps.ready(function () {
426        /*Карты "База знаний" справочник"*/
427        //map = new google.maps.Map(document.getElementById('map'), {
428        //   center: {lat: -34.397, lng: 150.644},
429        //   zoom: 8
430        // });
431        /*$('.railways-block__item-details-map').each(function () {
432            var name = $(this).attr('id');
433            var coord = $(this).data('coord');
434            myMap = new ymaps.Map(name, {
435                // При инициализации карты обязательно нужно указать
436                // её центр и коэффициент масштабирования.
437                center: coord, // Москва
438                zoom: 10
439            }, {
440                searchControlProvider: 'yandex#search'
441            });
442            myGeoObject = new ymaps.GeoObject({
443                // Описание геометрии.
444                geometry: {
445                    type: "Point",
446                    coordinates: coord
447                }
448            });
449            myMap.geoObjects.add(myGeoObject);
450        });*/
451
452
453        /*Карта о компании*/
454        if ($('div').is('#about_map')) {
455            map = new ymaps.Map("about_map", {
456                center: [44.200337, 43.126770],
457                zoom: 16
458            });
459            map.behaviors.disable('scrollZoom');
460            var saleOffice = new ymaps.Placemark([44.200337, 43.126770], {});
461            map.geoObjects.add(saleOffice);
462        }
463
464    });
465
466
467    //Загрузка файлов
468    $.fn.fileUploader = function (filesToUpload, sectionIdentifier, mainSection) {
469        var fileIdCounter = 0;
470
471        this.closest(".files").change(function (evt) {
472            console.log('sss');
473            var output = [];
474
475            for (var i = 0; i < evt.target.files.length; i++) {
476                fileIdCounter++;
477                var file = evt.target.files[i];
478                var fileId = sectionIdentifier + fileIdCounter;
479
480                filesToUpload.push({
481                    id: fileId,
482                    file: file
483                });
484
485                var removeLink = '<a class="removeFile delete-button" data-fileid="' + fileId + '"><i class="icon-cross"></i></a>';
486
487                output.push('<div class="uploaded-file-item">' +
488                    '<div class="img-wrapper">' +
489                    '<img src="/local/templates/transhub/img/text-document.svg" alt="">' +
490                    removeLink +
491                    '</div>' +
492                    '<div class="item-content">' +
493                    '<div class="name">' + file.name + '</div>' +
494                    '<div class="descr">' + file.type + ', ' + fileSize(file.size) + '</div>' +
495                    '</div>' +
496                    '</div>');
497            }
498            ;
499            if ($('#' + mainSection + ' .uploaded-files-row').html() == "При загрузке файлов то-то пошло Ð
499½Ðµ так. Прикрепите файлы снова и повторите попытку.") {
500                $('#' + mainSection + ' .uploaded-files-row').html('');
501            }
502            $('#' + mainSection + ' .uploaded-files-row').append(output.join(""));
503
504            //reset the input to null - nice little chrome bug!
505            evt.target.value = null;
506        });
507
508        $(document).on("click", ".removeFile", function (e) {
509            // e.preventDefault();
510
511            var fileId = $(this).parent().children("a").data("fileid");
512
513            // loop through the files array and check if the name of that file matches FileName
514            // and get the index of the match
515            for (var i = 0; i < filesToUpload.length; ++i) {
516                if (filesToUpload[i].id === fileId)
517                    filesToUpload.splice(i, 1);
518            }
519
520            $(this).parent().parent().remove();
521        });
522
523        this.clear = function () {
524            // for (var i = 0; i < filesToUpload.length; ++i) {
525            // if (filesToUpload[i].id.indexOf(sectionIdentifier) >= 0)
526            filesToUpload.splice(0, filesToUpload.length);
527            // }
528
529            $('#contact_with_director .uploaded-files-row').empty();
530        }
531
532        return this;
533    };
534
535    //Загрузка файлов не в popup
536    $.fn.fileUploaderPage = function (filesToUpload, sectionIdentifier, mainSection) {
537        var fileIdCounter = 0;
538        $("#files_answer_to_message").change(function (evt) {
539            var output = [];
540
541            for (var i = 0; i < evt.target.files.length; i++) {
542                fileIdCounter++;
543                var file = evt.target.files[i];
544                var fileId = sectionIdentifier + fileIdCounter;
545
546                filesToUpload.push({
547                    id: fileId,
548                    file: file
549                });
550
551                var removeLink = '<a class="removeFile delete-button" data-fileid="' + fileId + '"><i class="icon-cross"></i></a>';
552
553                output.push('<div class="uploaded-file-item">' +
554                    '<div class="img-wrapper">' +
555                    '<img src="/local/templates/transhub/img/text-document.svg" alt="">' +
556                    removeLink +
557                    '</div>' +
558                    '<div class="item-content">' +
559                    '<div class="name">' + file.name + '</div>' +
560                    '<div class="descr">' + file.type + ', ' + fileSize(file.size) + '</div>' +
561                    '</div>' +
562                    '</div>');
563            }
564            ;
565            if ($('#' + mainSection + ' .uploaded-files-row').html() == "При загрузке файлов то-то пошло не так. Прикрепите файлы снова и повторите попытку.") {
566                $('#' + mainSection + ' .uploaded-files-row').html('');
567            }
568            $('#' + mainSection + ' .uploaded-files-row').append(output.join(""));
569
570            //reset the input to null - nice little chrome bug!
571            evt.target.value = null;
572        });
573
574        $(document).on("click", ".removeFile", function (e) {
575            // e.preventDefault();
576
577            var fileId = $(this).parent().children("a").data("fileid");
578
579            // loop through the files array and check if the name of that file matches FileName
580            // and get the index of the match
581            for (var i = 0; i < filesToUpload.length; ++i) {
582                if (filesToUpload[i].id === fileId)
583                    filesToUpload.splice(i, 1);
584            }
585
586            $(this).parent().parent().remove();
587        });
588
589        this.clear = function () {
590            // for (var i = 0; i < filesToUpload.length; ++i) {
591            // if (filesToUpload[i].id.indexOf(sectionIdentifier) >= 0)
592            filesToUpload.splice(0, filesToUpload.length);
593            // }
594
595            $('#answer_to_message .uploaded-files-row').empty();
596        }
597
598        return this;
599    };
600
601    //Загрузка файлов формы "Письмо директору", "Написать компании", "Оставить отзыв"
602    var filesToUpload = [];
603    var filesToUploadСontractor = [];
604    var filesToUploadLeaveReview = [];
605    var filesToUploadLeaveMessage = [];
606
607    var files1Uploader = $("#files_contact_with_director").fileUploader(filesToUpload, "files_contact_with_director", "contact_with_director");
608    var files2Uploader = $("#files_contact_with_contractor").fileUploader(filesToUploadСontractor, "files_contact_with_contractor", "contact_with_contractor");
609    var files3Uploader = $("#files_leave_review").fileUploader(filesToUploadLeaveReview, "files_leave_review", "leave-review-popup");
610    var files4Uploader = $("#answer_to_message").fileUploaderPage(filesToUploadLeaveMessage, "files_answer_to_message", "answer_to_message");
611
612    $("#submit_contact_with_director").click(function (e) {
613        if ($("#contact_with_director form").valid()) {
614            e.preventDefault();
615
616            var formData = new FormData();
617
618            for (var i = 0, len = filesToUpload.length; i < len; i++) {
619                formData.append("file" + i, filesToUpload[i].file);
620            }
621
622            formData.append("message", $('#contact_with_director textarea').val());
623            // Отправляем запрос
624
625            $.ajax({
626                url: '/local/ajax/uploadfilesDirector.php',
627                type: 'POST',
628                data: formData,
629                cache: false,
630                dataType: 'json',
631                processData: false, // Не обрабатываем файлы (Don't process the files)
632                contentType: false, // Так jQuery скажет серверу что это строковой запрос
633                success: function (respond, textStatus, jqXHR) {
634                    if (typeof respond.error === 'undefined') {
635                        // Если все ОК
636                        var files_path = respond.files;
637                        var html = '';
638                        $.each(files_path, function (key, val) {
639                            html += val + '<br>';
640                        })
641                        // $('#contact_with_director .uploaded-files-row').html(html);
642                        $('#contact_with_director textarea').val('');
643                        files1Uploader.clear();
644                        $('#contact_with_director').removeClass("fadeIn active");
645                        $('#contat_with_director_success_popup').addClass("fadeIn active");
646
647                    } else {
648                        files1Uploader.clear();
649                        $('#contact_with_director .uploaded-files-row').html('При загрузке файлов то-то пошло Ð
649½Ðµ так. Прикрепите файлы снова и повторите попытку.');
650                    }
651
652                },
653                error: function (jqXHR, textStatus, errorThrown) {
654                    $('#contact_with_director .uploaded-files-row').html('При загрузке файлов то-то пошло не так. Прикрепите файлы снова и повторите попытку.');
655                    files1Uploader.clear();
656                }
657            });
658        }
659    });
660
661    $("#submit_contact_with_contractor").click(function (e) {
662        if ($("#contact_with_contractor form").valid()) {
663            e.preventDefault();
664
665            var formData = new FormData();
666
667            for (var i = 0, len = filesToUploadСontractor.length; i < len; i++) {
668                formData.append("file" + i, filesToUploadСontractor[i].file);
669            }
670
671            formData.append("message", $('#contact_with_contractor textarea').val());
672            formData.append("seller", $('#write_to_company').data('sellerid'));
673            formData.append("receiver", $('#write_to_company').data('receiverid'));
674            formData.append("company", $('#write_to_company').data('companyid'));
675            // Отправляем запрос
676
677            $.ajax({
678                url: '/local/ajax/messageToDriverOrClient.php',
679                type: 'POST',
680                data: formData,
681                cache: false,
682                dataType: 'json',
683                processData: false, // Не обрабатываем файлы (Don't process the files)
684                contentType: false, // Так jQuery скажет серверу что это строковой запрос
685                success: function (respond, textStatus, jqXHR) {
686                    if (typeof respond.error === 'undefined') {
687                        // Если все ОК
688                        var files_path = respond.files;
689                        var html = '';
690                        $.each(files_path, function (key, val) {
691                            html += val + '<br>';
692                        })
693                        // $('#contact_with_director .uploaded-files-row').html(html);
694                        $('#contact_with_contractor textarea').val('');
695                        files2Uploader.clear();
696                        $('#contact_with_contractor .uploaded-files-row').empty();
697                        $('#contact_with_contractor').removeClass("fadeIn active");
698                        //$('#contat_with_director_success_popup').addClass("fadeIn active");
699
700                        if(respond.redirect){
701                            window.location.href = respond.redirect_url;
702                        }
703
704                    } else {
705                        files2Uploader.clear();
706                        $('#contact_with_contractor .uploaded-files-row').html('При загрузке файлов то-то пошло не так. Прикрепите файлы снова и повторите попытку.');
707                    }
708
709                },
710                error: function (jqXHR, textStatus, errorThrown) {
711                    $('#contact_with_contractor .uploaded-files-row').html('При загрузке файлов то-то пошло не так. Прикрепите файлы снова и повторите попытку.');
712                    files4Uploader.clear();
713                }
714            });
715        }
716    });
717
718    // создание или открытие диалога в чате
719    $(document).on('click','#write_to_company',function(e) {
720        e.preventDefault();
721
722        $.ajax({
723            type: "POST",
724            url: '/chat/ajaxOpenChat.php',
725            data: {
726                sid: $('#write_to_company').data('sellerid'),
727                rid: $('#write_to_company').data('receiverid')
728            },
729            success: function (data) {
730                res = JSON.parse(data);
731                window.location.replace('/personal/message/'+res+'/');
732            },
733            error: function (data) {
734                alert('Ошибка выполнения запроса! Повторите попытку');
735            },
736            complete: function (data) {
737            }
738        });
739    });
740
741
742
743    $('body').on('click','#submit_answer_to_message',function(e){
744        if ($("#answer_to_message form").valid()) {
745
746            var formData = new FormData();
747
748            if($('#answer_to_message input').val() == ""){
749                return false;
750            }
751
752            formData.append("message", $('#answer_to_message input').val());
753            formData.append("seller", $('#submit_answer_to_message').data('sellerid'));
754            formData.append("receiver", $('#submit_answer_to_message').data('receiverid'));
755            formData.append("company", $('#submit_answer_to_message').data('companyid'));
756            formData.append("answertomsgid", $('#submit_answer_to_message').data('answertomsgid'));
757            // Отправляем запрос
758            $('.chat__button').addClass("disabled");
759            $.ajax({
760                url: '/local/ajax/messageToDriverOrClient.php',
761                type: 'POST',
762                data: formData,
763                cache: false,
764                dataType: 'json',
765                processData: false, // Не обрабатываем файлы (Don't process the files)
766                contentType: false, // Так jQuery скажет серверу что это строковой запрос
767                success: function (respond, textStatus, jqXHR) {
768                    if (typeof respond.error === 'undefined') {
769                        $.ajax({
770                            url: '/local/ajax/message_detail.php',
771                            type: 'post',
772                            data: {
773                                uri: $("#chat_uri").val()
774                            },
775                            success: function(data, status, xhr){
776                                $('.answer-container').html(data);
777                            }
778                        });
779                        $('.chat__input').val('');
780                        $('.chat__button').removeClass('disabled');
781
782                    } else {
783                        files2Uploader.clear();
784                        $('#csubmit_answer_to_message .uploaded-files-row').html('При загрузке файлов то-то пошло не так. Прикрепите файлы снова и повторите попытку.');
785                    }
786
787                },
788                error: function (jqXHR, textStatus, errorThrown) {
789                    $('#submit_answer_to_message .uploaded-files-row').html('При загрузке файлов то-то пошло не так. Прикрепите файлы снова и повторите попытку.');
790                    files2Uploader.clear();
791                }
792            });
793        }
794
795    });
796
797
798    $("#submit_leave_review").click(function (e) {
799        if ($("#leave-review-popup form").valid()) {
800            e.preventDefault();
801
802            var formData = new FormData();
803
804            for (var i = 0, len = filesToUploadLeaveReview.length; i < len; i++) {
805                formData.append("file" + i, filesToUploadLeaveReview [i].file);
806            }
807
808            formData.append("message", $('#leave-review-popup textarea').val());
809            formData.append("raiting", $('#leave-review-popup select').val());
810            formData.append("company", $('#leave_review_to_company').data('companyid'));
811            formData.append("companytype", $('#leave_review_to_company').data('companytype'));
812            // Отправляем запрос
813
814            $.ajax({
815                url: '/local/ajax/leasingCompanyLeaveReview.php',
816                type: 'POST',
817                data: formData,
818                cache: false,
819                dataType: 'json',
820                processData: false, // Не обрабатываем файлы (Don't process the files)
821                contentType: false, // Так jQuery скажет серверу что это строковой запрос
822                success: function (respond, textStatus, jqXHR) {
823                    if (typeof respond.error === 'undefined') {
824                        // Если все ОК
825                        var files_path = respond.files;
826                        var html = '';
827                        $.each(files_path, function (key, val) {
828                            html += val + '<br>';
829                        })
830                        // $('#contact_with_director .uploaded-files-row').html(html);
831                        $('#leave-review-popup textarea').val('');
832                        files3Uploader.clear();
833                        $('#leave-review-popup .uploaded-files-row').empty();
834                        $('#leave-review-popup').removeClass("fadeIn active");
835                        $('#contat_with_director_success_popup').addClass("fadeIn active");
836
837                    } else {
838                        files3Uploader.clear();
839                        $('#leave-review-popup .uploaded-files-row').html('При загрузке файлов то-то пошло Ð
839½Ðµ так. Прикрепите файлы снова и повторите попытку.');
840                    }
841
842                },
843                error: function (jqXHR, textStatus, errorThrown) {
844                    $('#leave-review-popup .uploaded-files-row').html('При загрузке файлов то-то пошло не так. Прикрепите файлы снова и повторите попытку.');
845                    files3Uploader.clear();
846                }
847            });
848        }
849    });
850
851    //Обработка удаления файла после реквизитов в ЛК Лизинговой компании
852    $(document).on('click', '.delete-button-leasing', function (e) {
853        var delfileid = $(this).data('fileid');
854        $.ajax({
855            url: '/local/ajax/deleteLeasingCompanyFile.php',
856            type: 'POST',
857            data: {
858                'fileid': $(this).data('fileid'),
859                'companyid': $(this).data('companyid')
860            },
861            success: function (respond, textStatus, jqXHR) {
862                $('#div_' + delfileid).remove();
863            },
864            error: function (jqXHR, textStatus, errorThrown) {
865            }
866        });
867    });
868
869    //обработка добавления файла  после реквизитов в ЛК Лизинговой компании
870    $(document).on('change', '#leasing_company_files', function () {
871        var files = this.files;
872        console.log(files);
873        // создадим объект данных формы
874        var data = new FormData();
875
876        // заполняем объект данных файлами в подходящем для отправки формате
877        $.each(files, function (key, value) {
878            data.append(key, value);
879        });
880
881        data.append('companyid', $(this).data('companyid'));
882
883        console.log(data);
884        $.ajax({
885            url: '/local/ajax/addLeasingCompanyFile.php',
886            type: 'POST',
887            data: data,
888            cache: false,
889            dataType: 'json',
890            processData: false,
891            contentType: false,
892            success: function (respond, status, jqXHR) {
893                // ОК - файлы загружены
894                if (typeof respond.error === 'undefined') {
895                    console.log(respond.html_success);
896                    $('.uploaded-files-row').html(respond.html_success);
897                }
898                // ошибка
899                else {
900                    console.log('ОШИБКА: ' + respond.data);
901                }
902            },
903            // функция ошибки ответа сервера
904            error: function (jqXHR, status, errorThrown) {
905                console.log('ОШИБКА AJAX запроса: ' + status, jqXHR);
906            }
907
908        });
909    });
910
911    //Обработка клика на "Заказать звонок"
912    $(document).on('click', '#callback_modal_submit', function (e) {
913        if ($("#callback_modal form").valid()) {
914            e.preventDefault();
915            $.ajax({
916                url: '/local/ajax/callbackform.php',
917                type: 'POST',
918                data: {
919                    'name': $("#callback_modal input[name='callback_name']").val(),
920                    'tel': $("#callback_modal input[name='callback_tel']").val(),
921                    'message': $("#callback_modal [name='callback_message']").val()
922                },
923                success: function (respond, textStatus, jqXHR) {
924
925                    $('#callback_modal').removeClass("fadeIn active");
926                    $('#call_back_success_popup').addClass("fadeIn active");
927                },
928                error: function (jqXHR, textStatus, errorThrown) {
929                }
930            });
931        }
932    });
933
934    //Обработка клика на "Отправить заявку" на странице контакты
935    $(document).on('click', '#contactsform_submit', function (e) {
936        if ($("#contactsform").valid()) {
937            e.preventDefault();
938            $.ajax({
939                url: '/local/ajax/callbackform.php',
940                type: 'POST',
941                data: {
942                    'name': $("#contactsform input[name='not_found_name']").val(),
943                    'tel': $("#contactsform input[name='not_found_tel']").val()
944                },
945                success: function (respond, textStatus, jqXHR) {
946                    $("#contactsform input[name='not_found_tel']").val('');
947                    $("#contactsform input[name='not_found_name']").val('');
948                    $('#call_back_success_popup').addClass("fadeIn active");
949                },
950                error: function (jqXHR, textStatus, errorThrown) {
951                }
952            });
953        }
954    });
955
956    $('[data-toggle="add-to-compare"]').on('click', function (e) {
957        $(this).parent().toggleClass('active');
958    });
959
960
961    $(document).on('change', '.choseCurrency', function (e) {
962        var showId = $(this).val();
963        $(".currency_title").each(function () {
964            $(this).css('display', 'none');
965        });
966        $(".currency_content_div").each(function () {
967            $(this).css('display', 'none');
968        });
969        $("#price_" + showId + "_title").css('display', 'flex');
970        $("#price_" + showId + "_content").css('display', 'flex');
971    });
972
973    $(document).on("click", ".sorting", function () {
974        if ($(this).hasClass('desc-sorting') || $(this).hasClass('active')) {
975            $(this).toggleClass('asc-sorting desc-sorting').siblings().removeClass('asc-sorting desc-sorting active');
976            sortotder = 'desc';
977        } else {
978            $(this).addClass('active asc-sorting').siblings().removeClass('asc-sorting desc-sorting active');
979            sortotder = 'asc';
980        }
981        var params = window
982            .location
983            .search
984            .replace('?', '')
985            .split('&')
986            .reduce(
987                function (p, e) {
988                    var a = e.split('=');
989                    p[decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
990                    return p;
991                },
992                {}
993            );
994        if (params["q"] != '' && params["q"] != undefined) {
995            window.location.replace((window.location.href).substring(0, (window.location.href).indexOf('?')) + '?q=' + params["q"] + '&sort=' + $(this).data('sortfield') + '&order=' + sortotder + '#set_filter');
996        } else {
997            window.location.replace((window.location.href).substring(0, (window.location.href).indexOf('?')) + '?sort=' + $(this).data('sortfield') + '&order=' + sortotder + '#set_filter');
998        }
999    });
1000});
1001
1002
1003$('#writeUs').on('submit', function (e) {
1004    var $this = $(this);
1005    e.preventDefault();
1006    $.ajax({
1007        url: '/local/ajax/writeSeller.php',
1008        type: 'POST',
1009        data: $this.serialize(),
1010        success: function (respond, textStatus, jqXHR) {
1011            tmp = JSON.parse(respond);
1012            if (tmp.result == "error") {
1013                $("#captcha_word").addClass("is-invalid");
1014                $("#captcha_word-error").html("Wrong captcha!");
1015            } else {
1016                $('input[name="feedback_name"]').val("");
1017                $('input[name="feedback_email"]').val("");
1018                $('input[name="feedback_tel"]').val("");
1019                $('textarea[name="feedback_message"]').val("");
1020                $('input[name="captcha_word"]').val("");
1021                $('#write_seller').addClass("fadeIn active");
1022            }
1023        },
1024        error: function (jqXHR, textStatus, errorThrown) {
1025        }
1026    });
1027});
1028
1029
1030//"Настройка оповещений в ЛК" Отменить и вернуться
1031$(document).on("click", ".reset-notify-cabinet", function () {
1032    window.location.href = '/personal/';
1033});
1034
1035//"Настройка оповещений в ЛК" Созранить
1036$(document).on("click", ".submit-notify-cabinet", function () {
1037    var email_message_notify = "N";
1038    if ($("#notif_2_email").is(':checked')) {
1039        email_message_notify = "Y";
1040    }
1041    $.ajax({
1042        url: '/local/ajax/editUserNotify.php',
1043        type: 'POST',
1044        data: {
1045            email_message_notify: email_message_notify
1046        },
1047        success: function (respond, status, jqXHR) {
1048            $('#thanks_popup_notify_user').addClass("fadeIn active");
1049
1050        },
1051        // функция ошибки ответа сервера
1052        error: function (jqXHR, status, errorThrown) {
1053
1054        }
1055
1056    });
1057});
1058
1059
1060//Yasha - start
1061$(function () {
1062    $("#type-user-js").select2({
1063        minimumResultsForSearch: -1,
1064        locale: 'ru',
1065        dropdownAutoWidth: true,
1066        width: '100%',
1067        allowClear: true,
1068        placeholder: function () {
1069            $(this).attr('data-placeholder');
1070        }
1071    }).on('select2:select select2:unselect', function (evt) {
1072
1073        $.ajax({
1074            url: '/local/ajax/raitingList.php',
1075            data: {
1076                iblockCode: $(this).val(),
1077            },
1078            dataType: 'html',
1079            type: 'post',
1080            success: function (data) {
1081                $(document).find('.ratings-block__table-body').html($(data).find('.ratings-block__table-body').html());
1082                $(document).find('.ratings-block__companies-count').html($(data).find('.ratings-block__companies-count').html());
1083                $(document).find('.rating-block').barrating({
1084                    theme: 'css-stars',
1085                    allowEmpty: true,
1086                    readonly: true
1087                });
1088
1089                $(document).find('.rate-select').barrating({
1090                    theme: 'css-stars',
1091                    allowEmpty: true,
1092                    onSelect: function (value, text, event) {
1093                        if (typeof (event) !== 'undefined') {
1094                            if ($(event.target).parents('.form-validate').length > 0) {
1095                                $(event.target).parents('.br-wrapper').find('select').valid();
1096                            }
1097                        }
1098                    }
1099                });
1100            },
1101        });
1102    });
1103    $(document).on('click', '.js-comparison-delete', function () {
1104        $(".compare-block__items-slider").slick(
1105            'slickRemove',
1106            $('.slick-slide').index($(this).parents('.compare-block__slide-item'))
1107        );
1108        $.ajax({
1109            url: '/comparison/',
1110            data: {
1111                action: 'DELETE_FROM_COMPARE_LIST',
1112                id: $(this).data('value')
1113            },
1114            dataType: 'html',
1115            type: 'get',
1116            success: function (data) {
1117                $(document).find('.compare-block__topbar').html($(data).find('.compare-block__topbar').html());
1118                $(document).find('.js-comparison-section').select2({
1119                    minimumResultsForSearch: -1,
1120                    locale: 'ru',
1121                    dropdownAutoWidth: true,
1122                    width: '100%',
1123                    allowClear: true,
1124                    placeholder: function () {
1125                        $(this).attr('data-placeholder');
1126                    }
1127                }).on('select2:select select2:unselect', selectUnselect);
1128                if ($('.js-comparison-delete').length == 0) {
1129                    location.reload();
1130                }
1131            },
1132        });
1133    });
1134
1135    $(document).on('click', '.js-compare-clear-all', function () {
1136        $('.js-comparison-delete').each(function () {
1137            $(this).trigger('click');
1138        });
1139        location.reload();
1140    });
1141
1142    function selectUnselect(evt) {
1143        $.ajax({
1144            url: '/comparison/',
1145            data: {
1146                section: $(this).val()
1147            },
1148            dataType: 'html',
1149            type: 'post',
1150            success: function (data) {
1151                $(document).find('.compare-block__slide-item').each(function (index, elem) {
1152                    $(document).find(".compare-block__items-slider").slick('slickRemove', $('.slick-slide').index($(elem)));
1153                });
1154                $(data).find('.compare-block__slide-item').each(function (index, elem) {
1155                    $(document).find(".compare-block__items-slider").slick('slickAdd', $(elem).parent().html(), $('.slick-slide').slick('slickCurrentSlide'));
1156                });
1157            },
1158        });
1159    }
1160
1161    $(document).find('.js-comparison-section').select2({
1162        minimumResultsForSearch: -1,
1163        locale: 'ru',
1164        dropdownAutoWidth: true,
1165        width: '100%',
1166        allowClear: true,
1167        placeholder: function () {
1168            $(this).attr('data-placeholder');
1169        }
1170    }).on('select2:select select2:unselect', selectUnselect);
1171    $(document).on('click', '.pass-auth', function () {
1172        $('.auth-password').toggleClass('auth-password-visible');
1173    });
1174
1175    $(document).on('change', '.type-transport-change', function () {
1176        var type = '';
1177        var id = $(this).attr('id');
1178        if (id == 'transport_type0' || id == 'type0') {
1179            type = 'auto';
1180        } else if (id == 'transport_type1' || id == 'type1') {
1181            type = 'railway';
1182
1183        } else if (id == 'transport_type2' || id == 'type3') {
1184            type = 'marine';
1185        } else {
1186            type = 'default';
1187        }
1188        $('.type-transport-item').each(function (index, element) {
1189            var dataType = $(element).data('type');
1190            if (dataType == type) {
1191                $(element).show();
1192            } else {
1193                $(element).hide();
1194            }
1195        });
1196    });
1197
1198    $(document).on('click', '.js-items-leasing-insurance', function () {
1199        var type = {};
1200        var stopCheck = true;
1201        $('.js-items-leasing-insurance').each(function (i, e) {
1202            if (e.checked) {
1203                stopCheck = false;
1204                type[i] = $(e).val();
1205            }
1206        });
1207        if (stopCheck)
1208            return false;
1209        else
1210            $.ajax({
1211                data: {filter: JSON.stringify(type)},
1212                dataType: 'html',
1213                type: 'post',
1214                success: function (data) {
1215                    $(document).find('#find_contractor_list').html($(data).find('#find_contractor_list').html());
1216                    console.log($(data).find('#find_contractor_list').html())
1217                },
1218            });
1219    });
1220
1221
1222    $(document).on('click', '.find-contractor__sort-button', function (e) {
1223        if (!$(this).hasClass('sort-button') && !$(this).hasClass('no-type')) {
1224            var type = {};
1225            var stopCheck = true;
1226            $('.js-items-leasing-insurance').each(function (i, e) {
1227                if (e.checked) {
1228                    stopCheck = false;
1229                    type[i] = $(e).val();
1230                }
1231            });
1232            var href = $(this).attr("data-sortname");
1233            if (stopCheck)
1234                return false;
1235            else
1236                $.ajax({
1237                    data: {
1238                        filter: JSON.stringify(type),
1239                        href: href
1240                    },
1241                    dataType: 'html',
1242                    type: 'post',
1243                    success: function (data) {
1244                        $(document).find('#find_contractor_list').html($(data).find('#find_contractor_list').html());
1245                        console.log($(data).find('#find_contractor_list').html())
1246                    },
1247                });
1248        }
1249    });
1250
1251    $(document).ready(function () {
1252        if (window.location.pathname == '/leasing/') {
1253            var type = {};
1254            var stopCheck = true;
1255            $('.js-items-leasing-insurance').each(function (i, e) {
1256                if (e.checked) {
1257                    stopCheck = false;
1258                    type[i] = $(e).val();
1259                }
1260            });
1261            if (stopCheck)
1262                return false;
1263            else
1264                $.ajax({
1265                    data: {filter: JSON.stringify(type)},
1266                    dataType: 'html',
1267                    type: 'post',
1268                    success: function (data) {
1269                        $(document).find('#find_contractor_list').html($(data).find('#find_contractor_list').html());
1270                        console.log($(data).find('#find_contractor_list').html())
1271                    },
1272                });
1273        }
1274
1275        if (window.location.pathname == '/personal/') {
1276            var paramsString = document.location.search;
1277            var searchParams = new URLSearchParams(paramsString);
1278            if (searchParams.get("newuser") == 'true') {
1279                $('#success_register_popup').addClass("fadeIn active");
1280                history.pushState(null, '', '/personal/');
1281            }
1282        }
1283    });
1284
1285    $(document).on('click', '.extend_popup_order', function () {
1286        $('.js-accept-continuation-order').data('id', $(this).data('value'));
1287    });
1288
1289    $("#js-accept-continuation-order-select").select2({
1290        minimumResultsForSearch: -1,
1291        locale: 'ru',
1292        dropdownAutoWidth: true,
1293        width: '100%',
1294        allowClear: true,
1295        placeholder: function () {
1296            $(this).attr('data-placeholder');
1297        }
1298    }).on('select2:select select2:unselect', function (evt) {
1299        $('.js-accept-continuation-order').data('value', $(this).val());
1300    });
1301    $(document).on('click', '.js-accept-continuation-order', function () {
1302        var id = $(this).data('id');
1303        $.ajax({
1304            url: '/local/ajax/updateOrder.php',
1305            data: {
1306                id: id,
1307                day: $(this).data('value')
1308            },
1309            dataType: 'json',
1310            type: 'post',
1311            success: function (data) {
1312                if (data.success) {
1313                    setTimeout(function () {
1314                        $('#thanks_subscribed_popup_order').find('span').text(data.date)
1315                        $('#thanks_subscribed_popup_order').addClass("fadeIn active");
1316                    }, 100);
1317                } else {
1318                    setTimeout(function () {
1319                        $('#thanks_subscribed_popup_order_error').addClass("fadeIn active");
1320                    }, 100);
1321                }
1322            },
1323        });
1324    });
1325
1326
1327    $(".js-find-count-items-cargo").select2({
1328        minimumResultsForSearch: -1,
1329        locale: 'ru',
1330        dropdownAutoWidth: true,
1331        width: '100%',
1332        allowClear: true,
1333        placeholder: function () {
1334            $(this).attr('data-placeholder');
1335        }
1336    }).on('select2:select select2:unselect', function (evt) {
1337        var count = $(this).val();
1338        $(document).find('.find-insert-item').find('.insert-item').css({'opacity': 0.2});
1339        setTimeout(function () {
1340            $.ajax({
1341                data: {
1342                    count: count
1343                },
1344                dataType: 'html',
1345                type: 'post',
1346                async: false,
1347                success: function (data) {
1348                    $(document).find('.find-insert-item').find('.insert-item').html($(data).find('.find-insert-item').find('.insert-item').html());
1349                },
1350                complete: function () {
1351                    $(document).find('.find-insert-item').find('.insert-item').css({'opacity': 1});
1352                }
1353            });
1354        }, 100);
1355    });
1356
1357    $(document).on('submit', "#from-leasing-insurance", function (e) {
1358        e.preventDefault();
1359        $('.custom-submit-button').click();
1360    });
1361
1362    $(document).on('click', '.custom-submit-button', function (e) {
1363        var name = $('#from-leasing-insurance').find('input[name=name]').val();
1364        var filter;
1365        $('.js-items-leasing-insurance').each(function (i, e) {
1366            if ($(e).prop('checked')) {
1367                filter = $(e).val();
1368            }
1369        });
1370        $.ajax({
1371            url: '/leasing/',
1372            data: {
1373                filter: filter,
1374                name: name
1375            },
1376            dataType: 'html',
1377            type: 'post',
1378            async: false,
1379            success: function (data) {
1380                $(document).find('#find_contractor_list').html($(data).find('#find_contractor_list').html());
1381                console.log($(data).find('#find_contractor_list').html())
1382            }
1383        });
1384
1385    });
1386});
1387
1388//Добавление объявления в архив/вынос из архива
1389$(document).on('click', '.add_del_to_arhive', function (e) {
1390    e.preventDefault();
1391    var itemText = $(this).parents('.popup-block').find('.popup-archive__textarea').val();
1392    var id = $(this).data('elementid');
1393    var active = $(this).data('active');
1394    if ($(this).attr('data-target') == '' || $(this).attr('data-target') === undefined) {
1395        $.ajax({
1396            url: '/local/ajax/addDelToArhive.php',
1397            data: {
1398                id: id,
1399                active: active,
1400                text: itemText
1401            },
1402            dataType: 'json',
1403            type: 'post',
1404            success: function (data) {
1405                if (data.success == "true") {
1406                    if (data.active == "yes") {
1407                        $(".div_element_" + id).removeClass("disabled");
1408                        $(".div_element_" + id + " .left").html("Активноe");
1409                        $(".div_element_" + id + " .right").css("display", "block");
1410                        if (data["days"] !== '' && data["hours"] !== '') {
1411                            $(".div_element_" + id + " .right .days").text(data["days"]);
1412                            $(".div_element_" + id + " .right .hours").text(data["hours"]);
1413                        }
1414                        $('#link_arhive_' + id).html('<span>Отправить в архив</span>');
1415                        $('#link_arhive_' + id).attr('data-target', '#send_to_archive_popup_' + id);
1416                    } else {
1417                        $(".div_element_" + id).addClass("disabled");
1418                        $(".div_element_" + id + " .left").html("В архиве");
1419                        $(".div_element_" + id + " .right").css("display", "none");
1420                        $('#link_arhive_' + id).html('<span>Вернуть из архива</span>');
1421                        $('#link_arhive_' + id).attr('data-target', '');
1422                    }
1423                    $('#link_arhive_' + id).data('active', data.active);
1424                } else {
1425                }
1426            },
1427        });
1428    }
1429});
1430
1431$(document).on('click', '.add_del_to_arhive_popup', function () {
1432    $(this).parents('.popup-block').find('.popup-block__close').trigger('click');
1433});
1434
1435//Карты
1436
1437$(function () {
1438    if ((window.location.href).indexOf('/knowledge/reference/') != '-1' || (window.location.href).indexOf('/knowledge/search/') != '-1') {
1439        $('.railways-block__item-details-map').each(function () {
1440            var name = $(this).attr('id');
1441            var lat = parseFloat($(this).data('lat'));//-37.790000 - 34.051467
1442            var lng = parseFloat($(this).data('lng'));//148.612222 - -6.751519
1443            myMap = new google.maps.Map(document.getElementById($(this).attr('id')), {
1444                center: {lat: lat, lng: lng},
1445                zoom: 10
1446            });
1447            var marker = new google.maps.Marker({
1448                position: {lat: lat, lng: lng},
1449                map: myMap,
1450                //title: 'Hello World!'
1451            });
1452        });
1453    }
1454    console.log('HERу');
1455    // if ($('div').is('#about_map')) {
1456    //     myMap = new google.maps.Map(document.getElementById('about_map'), {
1457    //         center: {lat: 44.213600, lng: 43.076865},
1458    //         zoom: 16
1459    //     });
1460    //     var marker = new google.maps.Marker({
1461    //         position: {lat: 44.213600, lng: 43.076865},
1462    //         map: myMap,
1463    //         icon: '/icon-map-marker.png'
1464    //         // icon: '/apple-touch-icon-76x76.png'
1465    //         //title: 'Hello World!'
1466    //     });
1467    //
1468    //     bounds = new google.maps.LatLngBounds(
1469    //         new google.maps.LatLng(-84.999999, -179.999999),
1470    //         new google.maps.LatLng(84.999999, 179.999999));
1471    //
1472    //     rect = new google.maps.Rectangle({
1473    //         bounds: bounds,
1474    //         fillColor: "#ffffff",
1475    //         fillOpacity: 0.3,
1476    //         strokeWeight: 0,
1477    //         map: myMap
1478    //     });
1479    // }
1480});
1481$(document).on('change', '.order-name-js', function () {
1482    var type = '';
1483    var id = $(this).attr('data-id');
1484    var text = $(this).attr('data-text');
1485    $('.order-name-js-input-name').text(text);
1486
1487    $('.order-name-js-input-code-name').hide();
1488    $('.order-name-js-input-code-e').hide();
1489    $('.order-name-js-input-code-e').find('input').val('');
1490    $('.order-name-js-input-code-g').hide();
1491    $('.order-name-js-input-code-g').find('input').val('');
1492
1493    $('input[value=011020]').trigger('click')
1494
1495    if (id == 0)
1496        $('.order-name-js-input-code-name').show();
1497    else if (id == 1)
1498        $('.order-name-js-input-code-e').show();
1499    else if (id == 2)
1500        $('.order-name-js-input-code-g').show();
1501});
1502
1503//Yasha - end
1504
1505if (window.location.pathname == '/') {
1506    $(document).on('click', '.form-swap-button', function () {
1507        var tmploc = $('input[name="locate_from"]').val();
1508        var tmprad = $('input[name="locate_from_rad"]').val();
1509        $('input[name="locate_from"]').val($('input[name="locate_to"]').val());
1510        $('input[name="locate_to"]').val(tmploc);
1511        $('input[name="locate_from_rad"]').val($('input[name="locate_to_rad"]').val());
1512        $('input[name="locate_to_rad"]').val(tmprad);
1513    });
1514}
1515
1516function openchat() {
1517    $('.hoverl_ebc').click();
1518}
1519
1520// проверяем куки и вызываем поап про куки
1521// function openModalNoScrollLock(hrefModal) {
1522
1523//     if ($(hrefModal).length > 0) {
1524//         $(hrefModal).trigger('beforeOpenModal').addClass('active');
1525
1526//         setTimeout(function () {
1527//             $(hrefModal).addClass('fadeIn').trigger('afterOpenModal');
1528//         }, 50);
1529
1530//         // bodyScrollLock.clearAllBodyScrollLocks();
1531//         // bodyScrollLock.disableBodyScroll(hrefModal, bodyScrollOptions);
1532//     }
1533
1534// }
1535
1536// function getCookie(name) {
1537//     var matches = document.cookie.match(new RegExp(
1538//         "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
1539//     ));
1540//     return matches ? decodeURIComponent(matches[1]) : undefined;
1541// }
1542
1543// function setCookie(name, value) {
1544//     var updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
1545//     document.cookie = updatedCookie;
1546// }
1547
1548// var preloader = function () {
1549//     var result = getCookie('shown');
1550//     if (result === undefined) {
1551//         openModalNoScrollLock(cookie);
1552//         setCookie('shown', true);
1553//     }
1554// }
1555// window.addEventListener('load', function () {preloader();});
1556
1557// $(document)
1558
1559
1560// Логика для методанных и записи в куки
1561const setCookie = (name, value) => {
1562    const updatedCookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)};path=/;max-age=31536000;`;
1563    document.cookie = updatedCookie;
1564};
1565
1566const getCookie = (name) => {
1567    const matches = document.cookie.match(new RegExp(`(?:^|; )${name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1')}=([^;]*)`));
1568    return matches ? decodeURIComponent(matches[1]) : undefined;
1569};
1570
1571const showCookie = () => {
1572    openModal('#cookie');
1573    const closeButton = document.querySelector('.cookie-close');
1574
1575    closeButton.addEventListener('click', () => {
1576        setCookie('agreeCookie', true);
1577    });
1578};
1579
1580const cookie = () => {
1581    const result = getCookie('agreeCookie');
1582    if (result === undefined) {
1583        showCookie();
1584    }
1585};
1586
1587cookie();
1588
1589
1590//Удаление картинки ЛК Грузоотправителя "Направления перевозок"
1591$(document).on("click", ".delete-button-direction-photo", function () {
1592    $.ajax({
1593        url: '/local/ajax/deleteDirectionPhoto.php',
1594        data: {
1595            companyid: $(this).data("companyid")
1596        },
1597        dataType: 'html',
1598        type: 'post',
1599        async: false,
1600        success: function (data) {
1601            $('.delete-button-direction-photo').css('display', 'none');
1602            $('#upload-direction-file').find('img').prop('src', '');
1603        }
1604    });
1605
1606});
1607
1608//Обновление капчи
1609$(document).on("click", ".new_captcha", function () {
1610    $.ajax({
1611        url: window.location,
1612        type: 'GET',
1613        dataType: 'html',
1614        success: function (data) {
1615            var newcontent = $(data).find('.form_content');
1616            $(".form_content").remove();
1617            $(".div-to-append-form").append(newcontent);
1618
1619        }
1620    });
1621});
1622
1623//Поиск по фразам.
1624var suggestView;
1625$(document).on('keyup', '.dropdown', function (e) {
1626    var obj = $(this);
1627    var val = $(this).val();
1628    var source = $(this).data('sorce');
1629
1630    var menu = obj.parent().find('.dropdown-menu');
1631
1632    var list = '';
1633
1634    var arr = [];
1635
1636    if (val.length > 0) {
1637        ymaps.suggest(val, {results: 5}).then(function (items) {
1638            console.log(items);
1639            if (items.length == 0) {
1640                $.ajax({
1641                    url: '/local/ajax/translate.php',
1642                    data: {'source': source, 'text': val},
1643                    dataType: 'json',
1644                    type: 'post',
1645                    success: function (data) {
1646                        ymaps.suggest(data).then(function (items) {
1647                            for (var i = 0; i < items.length; i++) {
1648                                var name = items[i].displayName;
1649                                name = name.replace(new RegExp(val, 'g'), '<strong>' + val + '</strong>');
1650                                list += '<li data-value="' + items[i].displayName + '">' + name + '</li>';
1651                            }
1652                            if (list != '')
1653                                menu.html(list);
1654                        });
1655                    },
1656                });
1657            } else {
1658
1659                for (var i = 0; i < items.length; i++) {
1660                    var name = items[i].displayName;
1661                    name = name.replace(new RegExp(val, 'g'), '<strong>' + val + '</strong>');
1662                    list += '<li class="dropdown-list" data-value="' + items[i].displayName + '">' + name + '</li>';
1663                }
1664                console.log(list);
1665                if (list != '') {
1666                    menu.html(list);
1667                    if (menu.attr('style') == 'display: none;') {
1668                        menu.attr('style', 'display: block;');
1669                    }
1670                }
1671            }
1672        });
1673    }
1674});
1675
1676$(".nav-item.reg_fiz_client").click(function () {
1677    $('#form-register-client label[for=check_show_in_list]').html("Отображать в списке грузоотправителей на сайте");
1678});
1679
1680$(".nav-item.reg_yur_client").click(function () {
1681    $('#form-register-client label[for=check_show_in_list]').html("Отображать в списке компаний на сайте");
1682});
1683
1684$(".nav-item.reg_fiz_seller").click(function () {
1685    $('#form-register-seller label[for=check_show_in_list]').html("Отображать в списке продавцов на сайте");
1686});
1687
1688$(".nav-item.reg_yur_seller").click(function () {
1689    $('#form-register-seller label[for=check_show_in_list]').html("Отображать в списке компаний на сайте");
1690});
1691
1692// $('.find-start-block__form-block').find('input[name="locate_from"], input[name="locate_to"]').typeahead({
1693//     ajax: '/local/ajax/?action=autocomplete&name=locate'
1694// });

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.