//манипуляции с ответом апи /* v1.4.49 - api_response */ function api_response(response) { //console.log('2'); if (response.data) { response.data.forEach(function (item) { //вставка if (item.method == 'append') { $(item.selector).append(item.content); } else if (item.method == 'prepend') { $(item.selector).prepend(); } else if (item.method == 'html') { $(item.selector).html(item.content); } else if (item.method == 'text') { $(item.selector).text(item.content); } else if (item.method == 'replaceWith') { $(item.selector).replaceWith(item.content); } //прокрутка else if (item.method == 'scrollTop') { var div = $(item.selector); div.scrollTop(div.prop('scrollHeight')); } else if (item.method == 'scroll') { //скрол $('html, body').animate({ scrollTop: $(item.selector).offset().top }, 1000); } //показать/скрыть else if (item.method == 'show') { $(item.selector).show(); } else if (item.method == 'hide') { $(item.selector).hide(); } else if (item.method == 'remove') { $(item.selector).remove(); } //атрибуты else if (item.method == 'prop') { $(item.selector).prop(item.prop, item.content); } else if (item.method == 'removeAttr') { $(item.selector).removeAttr(item.content); } else if (item.method == 'addClass') { $(item.selector).addClass(item.content); } else if (item.method == 'removeClass') { $(item.selector).removeClass(item.content); } //алерт else if (item.method == 'alert') { alert(item.content); } //переадресация else if (item.method == 'location') { window.location.href = item.content; } //обновление else if (item.method == 'reload') { window.location.reload(); } //окно, тут заменить на свое окно если не бутстрап else if (item.method == 'modal') { $(item.selector).modal(); } // закрыть окно else if (item.method == 'modal_close') { $(item.selector).modal('hide'); } //выполнение любого скрипта else if (item.method == 'script') { $('body').append(item.content); } else { alert(item.method); } }); } //todo код с ошибкой, сделать в всплывающем окне if (response.error_text) { alert(response.error_text); } else { if (response._error) alert(response._error); } } $(document).ready(function () { //валидация форм if ($.isFunction($.fn.validate)) { $('form.validate').each(function () { $(this).validate({ //настройка стилей валидации //.form-group обертка для всех полей errorPlacement: function (error, element) { error.appendTo(element.closest(".form-group")); }, highlight: function (element, errorClass, validClass) { //console.log('highlight'); $(element).addClass(errorClass); $(element).closest('.form-group').addClass(errorClass); }, unhighlight: function (element, errorClass, validClass) { //console.log('unhighlight'); $(element).removeClass(errorClass); $(element).closest('.form-group').removeClass(errorClass); } }) }); } //очитска урл от путстых значений $('form.form_clear').submit(function () { $(this).find('select,input').each(function () { if ($(this).val() == '' || $(this).val() == '0-0') $(this).removeAttr('name'); }); }); //отправка формы аджаксом - v1.2.22 $(document).on('submit', 'form.ajax', function () { var form = $(this), formData = new FormData($(this).get(0)), //путь куда отправляется форма action = $(this).data('action'), //окно которое открывается при успехе //window_success = $(this).data('window_success'), //блок куда показывать ошибки сгенерированные на пхп //message_box = $('.message_box',this), valid = true; //обработку делаем только если указан data-action, иначе форма ведет себя как обычная if (action) { //валидация if ($(this).hasClass('validate')) { //jquery_validate.js if ($.isFunction($.fn.validate)) { valid = false; if ($(this).valid()) { valid = true; } } } //делаем отправку только если форма валидная if (valid) { $.ajax({ url: action, type: $(form).attr('method'), dataType: 'json', contentType: false, processData: false, data: formData, cache: false, beforeSend: function () { $(form).find('button[type=submit]').addClass('disabled'); }, success: function (json, textStatus) { //очистка формы if (json.success) { $('input:not([type=submit]):not([name=captcha]):not([type=hidden]),textarea,select', form).prop('value', null); } api_response(json); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); }, complete: function (XMLHttpRequest, textStatus) { setTimeout(function () { $(form).find('button[type=submit]').removeClass('disabled'); }, 1000); } }); } return false; } }); //аналоги form.ajax не для форм (ссылки, кнопки и т.д.) $(document).on('click', '[data-api*="/"]', function (e) { e.preventDefault(); var $data = $(this).data(), $url = $data.api, $btn = $(this); //если уже нажали и небыло ответа аджакса то ничего не делать if (!$btn.hasClass('js_wait')) { $btn.addClass('js_wait'); //удаляем датаатрибут чтобы не дублировать в запросе delete $data.api; $.ajax({ method: "GET", type: 'JSON', url: $url, data: $data, cache: false }).done(function ($response) { api_response($response); }).fail(function () { alert("error"); }).always(function () { $btn.removeClass('js_wait'); }); //возвращаем назад дата атрибут $data.api = $url; } //return false; }); //мультичексбокс $(document).on("change", '.form_multi_checkbox .data input', function () { var arr = []; var i = 0; $(this).parents('.data').find('input:checked').each(function () { arr[i] = $(this).val(); i++; }); $(this).parents('.data').next('input').val(arr); }); //min-max $(document).on("change", '.form_input2 input', function () { var min = parseInt($(this).parents('.form_input2').find('input.form_input2_1').val()); var max = parseInt($(this).parents('.form_input2').find('input.form_input2_2').val()); $(this).parents('.form_input2').find('input[type=hidden]').val(min + '-' + max); }); $(document).on("change", '.subscription_checkbox input[name=auto_paid]', function () { $(this).parents('form').submit(); }); //прогресс в пагинации function paginationProgress(e) { if ($('.pagination_ajax_secondary').length) { let paginationNumberOne = +$('.pagination_ajax_one').text(); let paginationNumberTwo = +$('.pagination_ajax_two').text(); const precent = Math.floor(paginationNumberOne / (paginationNumberTwo / 100)); let paginationProgressLine = $('.pagination_ajax_progress span'); paginationProgressLine.css('width', `${precent}%`); } } paginationProgress(); //v1.2.64 пагинатор на ajax $(document).on("click", '.pagination_ajax .pagination_ajax_btn a', function () { var url = $(this).attr('href'), box = $(this).closest('.pagination_ajax'); $.post(url, { action: 'ajax', }, function (data) { $(box).replaceWith(data); paginationProgress(); //добавляем в историю браузера //window.history.pushState(null, null, url); }); return false; }); /* //автоматическая догрузка страниц для ajax_more if ($('.pagination_ajax').length) { var pagination_ajax_url = ''; //v1.2.90 $('.pagination a', '.pagination_ajax').trigger('click'); $(window).scroll(function () { //console.log('scroll'); if ($('.pagination_ajax').length) { var box = $('.pagination_ajax'), document_top = $(document).scrollTop(), window_height = $(window).height(), box_top = $(box).offset().top, box_height = $(box).height(), current_url = $('.pagination a', box).attr('href'); if (document_top + window_height > box_top && document_top - box_top < box_height) { if (current_url != pagination_ajax_url) { //v1.2.90 $('.pagination a', box).trigger('click'); pagination_ajax_url = current_url; //v1.2.90 } } } }); } /**/ //открытие языка $(document).on("click", '.languages_title', function () { $(this).toggleClass('active'); $(this).next().toggleClass('open'); }); //закрытие языка $(document).on("click", function (e) { if (!$(e.target).closest(".languages_title, .languages_drop").length) { $('.languages_drop').removeClass('open'); $('.languages_title').removeClass('active'); } }); //select2 $('.form__select .form-control').select2({ minimumResultsForSearch: Infinity, }); //открытие меню профиля //$('.header_user_btn').on("click", function () { $(document).on("click", '.header_user_btn', function () { $(this).parent().toggleClass('open'); }); //закрытие меню профиля $(document).on("click", function (e) { if (!$(e.target).closest(".header_user").length) { $('.header_user').removeClass('open'); } }); // $(document).on('click', '.pagination_ajax_btn a', function (e) { // console.log(11); // paginationProgress(); // }) //сложить сайдбар $(document).on("click", '.sidebar_btn', function () { $(this).closest('.sidebar').toggleClass('sidebar_close'); $('.account_content').toggleClass('sidebar_close'); }); //закрывать модалку свайпом вниз на мобилке $(".modal_swipe_close").swipe({ swipeStatus: function (event, phase, direction, distance, duration, fingerCount, fingerData, currentDirection) { if (phase == "end") { if (direction == 'down') { console.log('down'); $(this).closest('.modal').modal('hide') } } }, triggerOnTouchEnd: false, threshold: 20 }); //закрывать меню свайпом вниз на мобилке $(".menu_all_wrapper").swipe({ swipeStatus: function (event, phase, direction, distance, duration, fingerCount, fingerData, currentDirection) { if (phase == "end") { if (direction == 'down') { console.log('down'); $(this).removeClass('open'); $('.menu_link_all').removeClass('active'); } } }, triggerOnTouchEnd: false, threshold: 20 }); //пункты меню, которые не входят, скрываются function responseMenu() { if ($(window).width() < 992) { $('.menu_all_wrapper .menu_item').appendTo('.menu'); let items = $('.menu .menu_item'); let max_width = $('.menu').width() - $('.menu_all_btn').outerWidth(); let width = 0; let hide_from = 0; items.css({ 'width': 'auto' }); items.each(function (index) { if (width + $(this).outerWidth() > max_width) { return false; } else { hide_from = index; width += $(this).outerWidth(); } }); if (hide_from < items.length - 1) { items.eq(hide_from).nextAll('.menu_item').appendTo('.menu_all_wrapper'); $('.menu_all_btn').show(); } else { $('.menu_all_btn').hide(); } } } $(window).on('resize', function () { responseMenu(); }).trigger('resize'); //Показ не входивших пунктов при клике на троеточие $(document).on('click', '.menu_all_btn', function () { $('.menu_all_wrapper').toggleClass('open'); $(this).find('.menu_link_all').toggleClass('active'); }); //закрытие не входивших пунктов меню, при клике на страницу $(document).on('click', function (e) { if (!$(e.target).closest(".menu_all_btn,.menu_all_wrapper").length) { $('.menu_all_wrapper').removeClass('open'); $('.menu_link_all').removeClass('active'); } e.stopPropagation(); }); //Закрытие сообщения $(document).on('click', '.message_close', function () { $('.menu_all_wrapper').toggleClass('open'); $(this).parents('.message_box').hide(); }); //маска на инпут с Суммой вывода $('.additionally_modal').on('show.bs.modal', function (e) { document.querySelectorAll('.mask_input_profit .form_input').forEach((e) => { $('.mask_input_profit .form_input').on('focus', function () { const phoneMask = IMask(e, { mask: 'DD.YY', lazy: false, scale: 2, blocks: { YY: { mask: '\\0\\0', }, DD: { max: 10000, min: 10, mask: Number, } } }) }) }); document.querySelectorAll('.mask_input_withdrawal .form_input').forEach((e) => { $('.mask_input_withdrawal .form_input').on('focus', function () { const phoneMask = IMask(e, { mask: 'DD', lazy: false, scale: 2, blocks: { DD: { max: 10000, min: 10, mask: Number, } } }) }) }); }); //Закрытие уведомления $(document).on('click', '.notification_block_close', function () { $(this).parent().hide(); }); /* document.querySelectorAll('.bots_mask_input .form_input').forEach((e) => { $('.bots_mask_input .form_input').on('focus, change', function () { if($(this).val()>0){ const phoneMask = IMask(e, { mask: 'DD.YY', lazy: false, scale: 2, blocks: { YY: { mask: 'USDT', }, DD: { mask: Number, } } }) } else{ $(this).val(''); } }) });*/ $(document).on('click', '.bots_info_btn', function () { $(this).toggleClass('active') $(this).next().slideToggle(); }); //tooltip $('[data-toggle="tooltip"]').tooltip({ // trigger: 'click', }); //отображение имени загруженого файла $('input[type="file"]').change(function () { let files = $(this).val(); let filename = files.replace(/C:\\fakepath\\/i, '').split("\\"); $('.file_new_name').text(filename); }); //календарь $.fn.datepicker.dates['ru'] = { days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"], daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб"], daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"], months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"], monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"], today: "Сегодня", clear: "Очистить", format: "dd.mm.yyyy", weekStart: 1, monthsTitle: 'Месяцы' }; $('.datepicker input').datepicker({ format: 'mm/dd/yyyy', language: 'ru', //orientation: "bottom auto", todayHighlight: true, }); // $('.navigator_item_btn').on('click', function (e) { // $(this).parent().toggleClass('open'); // }); // $('.tasks_list .collapse').on('shown.bs.collapse', function () { // $(this).parent().addClass('active'); // }); // $('.tasks_list .collapse').on('hidden.bs.collapse', function () { // $(this).parent().removeClass('active'); // }); // $('.tasks_list .collapse').first().collapse('show'); // $('.tasks_list .card.disabled').on('click', function (e) { // e.stopPropagation(); // }); // //открытие смайлов // $(document).on("click", '.smiles_btn', function (e) { // $(this).parent().toggleClass('open'); // }); // //закрытие смайлов // $(document).on("click", function (e) { // if (!$(e.target).closest(".smiles_btn, .character-list__list").length) { // $('.smiles-wrapper').removeClass('open'); // } // }); // //открытие диалогов // $('.user_list_left_btn').on("click", function () { // $(this).parent().toggleClass('open'); // }); // $('.chat_user_list').on("click", function () { // $('.user_list_left_wrapper').removeClass('open'); // }); // $('.chat_groups').on("click", function () { // $('.user_list_left_wrapper').addClass('open'); // }); });