Advertisement
aljajazva

Untitled

Sep 28th, 2020
903
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. // Иниациализация фильтров диапазона при загрузке
  3. $('.af_pf_input').each(function(){
  4.    var af_pf_input = $(this),
  5.        min = af_pf_input.data('min'),
  6.        max = af_pf_input.data('max'),
  7.        after = af_pf_input.data('after'),
  8.        value = af_pf_input.val() != '' ? af_pf_input.val().split(',') : new Array('', '');
  9.    af_pf_input.ionRangeSlider({
  10.        type: "double",
  11.        min: min,
  12.        max: max,
  13.        from: value[0],
  14.        to: value[1],
  15.        hide_min_max: true,
  16.        hide_from_to: true,
  17.        grid: false,
  18.        postfix: "грн.",
  19.        onStart: function(data){ // Срабатывает после инициализации
  20.            af_pf_input.parent().prepend('<div class="af_range_val"><i>'+data.from+' - '+data.to+' '+after+'</i><span class="af_delete"></span></div>');
  21.  
  22.            if(data.from != min || data.to != max){
  23.                af_pf_input.parent().find('.af_delete').css('display', 'inline-block');
  24.            }
  25.            af_search_active_filters();
  26.        },
  27.        onChange: function(data){ // Срабатывает при изменении
  28.            if(data.from == min && data.to == max){
  29.                af_pf_input.removeAttr('readonly').attr('value', '');
  30.                af_pf_input.parent().find('.af_delete').hide();
  31.            }else{
  32.                af_pf_input.removeAttr('readonly').attr('value', data.from+','+data.to);
  33.                af_pf_input.parent().find('.af_delete').css('display', 'inline-block');
  34.            }
  35.            af_pf_input.parent().find('.af_range_val i').text(data.from+' - '+data.to+' '+after);
  36.  
  37.            af_search_active_filters();
  38.  
  39.        },
  40.        onFinish: function(data){ // Срабатыва
  41. ет при изменении
  42.            change_slider_filter(af_pf_input);
  43.        }
  44.    });
  45.  
  46.    // Сброс конкретного фильтра диапазона при клике
  47.    af_pf_input.parent().find('.af_delete').click(function(){
  48.        af_pf_input.data("ionRangeSlider").update({from: min, to: max});
  49.        af_pf_input.removeAttr('readonly').attr('value', '');
  50.        af_pf_input.parent().find('.af_range_val i').text(min+' - '+max+' '+after);
  51.        $(this).hide();
  52.        af_search_active_filters();
  53.  
  54.        var filter = af_pf_input;
  55.        var name = $(filter).attr('name');
  56.        var url = find_right_url();
  57.        $.ajax({
  58.            type: 'POST',
  59.            url: '/mods/a.function.php',
  60.            data: 'aj=102&name='+name+'&url='+url,
  61.            dataType: "json",
  62.            success: function (response) {
  63.                update_apartments_html(response);
  64.            }
  65.        });
  66.    });
  67. });
  68.  
  69. // Открытие/закрытие выпадающего списка первого фильтра
  70. $(document).on('click mouseenter', '.af_dropdown', function(){
  71.    var parent = $(this).parents('.af_item');
  72.    if(parent.hasClass('active')){
  73.        parent.removeClass('active').find('.af_dropdown_block').slideUp(100);
  74.        return
  75.    }
  76.    parent.addClass('active').find('.af_dropdown_block').slideDown(100);
  77. });
  78.  
  79. $(document).on('mouseleave', '.af_item', function(){
  80.    $(this).removeClass('active').find('.af_dropdown_block').slideUp(100);
  81. });
  82.  
  83. var window_w = $(window).width();
  84. $(window).resize(function() {
  85.    window_w = $(window).width();
  86. });
  87.  
  88. // Закрытие выпадающего списка первого фильтра если клик не по нему
  89. $(document).click(function(e){
  90.    if( window_w > 767){
  91.        var af_dropdown_block = $('.af_item_1');
  92.        if (!af_dropdown_block.is(e.target)
  93.            && af_dropdown_block.has(e.target).length === 0
  94.            && $('.af_item_1 .af_dropdown_block').css('display') == 'block'){
  95.            af_dropdown_block.removeClass('active').find('.af_dropdown_block').slideUp(100);
  96.        }
  97.    }
  98. });
  99.  
  100. // Закрытие выпадающего списка второго фильтра если клик не по нему
  101. $(document).click(function(e){
  102.    if( window_w > 767){
  103.        var af_dropdown_block = $('.af_item_2');
  104.        if (!af_dropdown_block.is(e.target)
  105.            && af_dropdown_block.has(e.target).length === 0
  106.            && $('.af_item_2 .af_dropdown_block').css('display') == 'block'){
  107.            af_dropdown_block.removeClass('active').find('.af_dropdown_block').slideUp(100);
  108.        }
  109.    }
  110. });
  111.  
  112. // Поиск активного параметра первого фильтра при загрузке
  113. $('.af_dropdown_block .af_dropdown_section a.active').each(function(){
  114.    af_dropdown_set_title($(this));
  115. });
  116.  
  117. // Установка заголовка у первого фильтра при клике
  118. $('.af_dropdown_block a').click(function(){
  119.    $(this).parents('.af_dropdown_block').find('a').removeClass('active');
  120.    $(this).addClass('active');
  121.  
  122.    if(af_dropdown_set_title($(this))){
  123.        $(this).parents('.af_item').find('.af_queue span').html($(this).text());
  124.    }
  125.    af_search_active_filters();
  126.    return false;
  127. });
  128.  
  129. //Ф-ция изменения заголовка у первого фильтра
  130. function af_dropdown_set_title(a_active){
  131.    return true;
  132.    if(a_active.is('.af_all_sections')){return true;}
  133.    var a_parent = a_active.parent(),
  134.        parent_span_text = a_parent.find('span').text();
  135.  
  136.    num_section = parent_span_text.match(/\d+-[а-яА-ЯёЁ]\s/i);
  137.    num_section = num_section[0].replace(/\s/g, '');
  138.  
  139.    year = parent_span_text.match(/([а-яА-ЯёЁ]{3}\.\s\d{4})/i);
  140.    year = year[0].substr(0,1).toUpperCase() + year[0].substr(1);
  141.  
  142.    result = num_section+', '+a_active.text().toLowerCase()+' '+year;
  143.    a_parent.parents('.af_item').find('.af_queue span').html(result);
  144.    $('.af_all_sections').removeClass('active');
  145.  
  146.    return false;
  147. }
  148.  
  149. // Сброс фильтров при клике
  150. $('.af_reset_filters, .af_mobile_reset').click(function(){
  151.    if($('.af_item_1 .af_dropdown_block').find('a').not('.af_all_sections').hasClass('active')){
  152.        $('.af_item_1 .af_dropdown_block').find('a').removeClass('active');
  153.        $('.af_item_1 .af_dropdown_block').parent().find('.af_queue span').html($('.af_all_sections').text());
  154.        af_search_active_filters();
  155.    }
  156.  
  157.    $('.af_item_2').find('input[type="checkbox"]').not('.all_variant').each(function(){
  158.        $(this).prop('checked', false);
  159.    });
  160.    $('.af_item_2').find('.af_queue span').html($('.af_item_2 .all_variant').parent().find('span').text());
  161.  
  162.    // if($('.af_item').find('.af_delete').css('display') == 'inline-block'){
  163.    $('.af_pf_input').each(function(){
  164.        var min = $(this).data('min'),
  165.            max = $(this).data('max'),
  166.            after = $(this).data('after');
  167.        $(this).data("ionRangeSlider").update({from: min, to: max});
  168.        $(this).removeAttr('readonly').attr('value', '');
  169.        $(this).parent().find('.af_range_val i').text(min+' - '+max+' '+after);
  170.        $(this).parents('.pf_rngstyle_html5').find('.af_delete').hide();
  171.    });
  172.    af_search_active_filters();
  173.    reset_all_filters();
  174.    // }
  175. });
  176.  
  177. //Ф-ция возвращает true когда хотябы один фильтр найден, иначе false
  178. function af_search_active_filters(){
  179.    var isset_filters = false;
  180.    $('.af_item').each(function(){
  181.        if($(this).hasClass('af_item_1')){
  182.            if($(this).find('a').not('.af_all_sections').hasClass('active')){
  183.                isset_filters = true;
  184.            }
  185.        }else if($(this).hasClass('af_item_2')){
  186.            $(this).find('input[type="checkbox"]').not('.all_variant').each(function(){
  187.                if($(this).prop('checked')){
  188.                    isset_filters = true;
  189.                    return false;
  190.                }
  191.            });
  192.        }else{
  193.            if($(this).find('.af_delete').css('display') == 'inline-block'){
  194.                isset_filters = true;
  195.            }
  196.        }
  197.    });
  198.  
  199.    if(isset_filters){
  200.        $('.af_reset_filters, .af_filters_mob').addClass('show');
  201.    }else{
  202.        $('.af_reset_filters, .af_filters_mob').removeClass('show');
  203.    }
  204. }
  205.  
  206. $('.af_mobile_close, .af_filters_mob').click(function(){
  207.    $('.apartments_filter').fadeToggle();
  208. });
  209.  
  210.  
  211. // Изменеие заголовка второго фильтра при клике
  212. $('.af_item_2 input[type="checkbox"]').change(function(){
  213.    af_dropdown2_set_title($(this));
  214.    af_search_active_filters();
  215. });
  216.  
  217. // Поиск активных параметров второго фильтра при загрузке
  218. $('.af_item_2 input[type="checkbox"]').each(function(){
  219.    af_dropdown2_set_title($(this));
  220.    af_search_active_filters();
  221. });
  222.  
  223. //Ф-ция изменения заголовка второго фильтра
  224. function af_dropdown2_set_title(checkbox){
  225.    if(checkbox.hasClass('all_variant')){ // Если это .all_variant
  226.        if(checkbox.prop('checked')){ // Если .all_variant отмечено
  227.            // Перебираем все чекбоксы кроме .all_variant и сбрасываем
  228.            checkbox.parents('.af_dropdown_block').find('input[type="checkbox"]').not(checkbox).each(function(){
  229.                $(this).prop('checked', false);
  230.            });
  231.            checkbox.parents('.af_item').find('.af_queue span').html(checkbox.parent().find('span').text());
  232.        }
  233.    }else{ // Если это не .all_variant
  234.        // Ищем .all_variant и сбрасываем
  235.        var all_variant = checkbox.parents('.af_dropdown_block').find('.all_variant');
  236.        if(all_variant.prop('checked')) all_variant.prop('checked', false);
  237.  
  238.  
  239.        var params_title = new Array();
  240.        checkbox.parents('.af_dropdown_block').find('input:checkbox:checked').not('.all_variant').each(function(){
  241.            params_title.push($(this).parent().find('span').text());
  242.        });
  243.  
  244.        if(params_title.length == 0){ // Не выбрано параметров
  245.            checkbox.parents('.af_item').find('.af_queue span').html(all_variant.parent().find('span').text());
  246.        }else{
  247.            var rooms = '', befor_rooms = '';
  248.            for (var i=0; i < params_title.length; i++) {
  249.                string = params_title[i].match(/\d+/i);
  250.                if(string !== null){
  251.                    rooms+= (rooms == '') ? string : ', '+string;
  252.                }else{
  253.                    var title_arr = params_title[i].split(' ');
  254.                    for (var j=0; j < title_arr.length; j++) {
  255.                        if(j+1 == title_arr.length){
  256.                            befor_rooms+= title_arr[j].substr(0, 4)+'.';
  257.                        }else{
  258.                            befor_rooms+= title_arr[j].substr(0, 4)+'. ';
  259.                        }
  260.                    }
  261.                    befor_rooms+=', ';
  262.  
  263.                }
  264.            }
  265.            if(rooms != '') rooms+=' комнат';
  266.            var result = befor_rooms+rooms;
  267.            result = result.replace(/,\s$/, '').toLowerCase();
  268.            result = result.charAt(0).toUpperCase() + result.substr(1);
  269.  
  270.            checkbox.parents('.af_item').find('.af_queue span').html(result);
  271.        }
  272.    }
  273. };
  274.  
  275. // Обновление ссылок в фильтре очередей/секций
  276. function update_stage_section_url(full_new_url) {
  277.    var new_url = full_new_url.replace(/^\/.*?(\/|$)/, '/')
  278.        .replace(/.*?\/stage-.*?(\/|$)/, '/')
  279.        .replace(/.*?\/section-.*?\//, '/');
  280.    $('a[section]').each(function(index, element){
  281.        element = $(element);
  282.        var base_link = element.attr('base-link');
  283.        element.attr('href', base_link + new_url);
  284.    });
  285. }
  286.  
  287. function update_apartments_html(response) {
  288.    if (window.filterurl === undefined){
  289.        window.filterurl = '/apartmentsearch/'
  290.    }
  291.    if (window.location.pathname.indexOf('/apartmentsearch') != -1){
  292.        $($.find('div#filter_apartments')).html(response.html);
  293.        $($.find('div#filter_pagination')).html(response.pagination);
  294.        window.history.pushState(response.new_url, "", response.new_url);
  295.        $($.find('h2#meta-text span')).html(response.metatext);
  296.        $($.find('span#count1')).html(response.count);
  297.        update_stage_section_url(response.new_url);
  298.    } else {
  299.        window.filterurl = response.new_url;
  300.    }
  301. }
  302. //определяем откуда нам брать значения фильтров
  303. // в случае страницы фильтров это урл
  304. // в случае остальных это спрятанная переменная window.filterurl mk
  305. function find_right_url() {
  306.    var url;
  307.    if (window.location.pathname.indexOf('/apartmentsearch') != -1){
  308.        url = window.location.pathname;
  309.    } else {
  310.        url = window.filterurl;
  311.    }
  312.    return url;
  313.    url = find_right_url()
  314. }
  315. //обработчик кнопки фильтров для блока на сторонних страницах
  316. $('button#filter-bottom').on('click',function (event) {
  317.    event.preventDefault();
  318.    if (window.filterurl === undefined){
  319.        window.filterurl = '/apartmentsearch/'
  320.    }
  321.    window.location.href = window.filterurl;
  322.    event.stopPropagation();
  323. })
  324.  
  325. function reset_all_filters() {
  326.    $.ajax({
  327.        type: 'POST',
  328.        url: '/mods/a.function.php',
  329.        data: 'aj=101',
  330.        dataType: "json",
  331.        success: function (response) {
  332.            update_apartments_html(response);
  333.        }
  334.    });
  335. }
  336.  
  337. // Обработчик изменения значений ползунков
  338. function change_slider_filter(filter){
  339.    var name = $(filter).attr('name');
  340.    var value = $(filter).val();
  341.    var url = find_right_url();
  342.    $.ajax({
  343.        type: 'POST',
  344.        url: '/mods/a.function.php',
  345.        data: 'aj=100&name='+name+'&value='+value+'&url='+url,
  346.        dataType: "json",
  347.        success: function (response) {
  348.            update_apartments_html(response);
  349.        }
  350.    });
  351. }
  352.  
  353. // Обработчик изменения сортировки
  354. $('select#sort_apartments').on('change', function (event) {
  355.    var url = find_right_url();
  356.    var sort = $(this).val();
  357.    $.ajax({
  358.        type: 'POST',
  359.        url: '/mods/a.function.php',
  360.        data: 'aj=103&url='+url+'&sort='+sort,
  361.        dataType: "json",
  362.        success: function (response) {
  363.            update_apartments_html(response);                }
  364.    });
  365. })
  366.  
  367. // Обработчик выбора секции/очереди
  368. $('a[section]').on('click', function (event) {
  369.    var url = $(this).attr('href');
  370.    var stage = url.match(/\/stage-(.*?)(\/|$)/);
  371.    var section = url.match(/\/section-(.*?)(\/|$)/);
  372.    var sectionParameter = '';
  373.    if ((section !== null) && (section[1] !== undefined)) {
  374.        sectionParameter = '&section='+section[1];
  375.    }
  376.    $.ajax({
  377.        type: 'POST',
  378.        url: '/mods/a.function.php',
  379.        data: 'aj=104&stage='+stage[1]+sectionParameter+'&new_url='+url,
  380.        dataType: "json",
  381.        success: function (response) {
  382.            update_apartments_html(response);                }
  383.    });
  384. });
  385.  
  386. // Обработчик выбора секции/очереди
  387. $('input[name="count_room[]"]').on('change', function (event) {
  388.    var url = find_right_url();
  389.    var checkedRooms = $('input:checkbox[name="count_room[]"]:checked')
  390.        .map(function() {
  391.            return $(this).val();
  392.        }).get().join(';');
  393.    $.ajax({
  394.        type: 'POST',
  395.        url: '/mods/a.function.php',
  396.        data: 'aj=100&name=number_rooms' + '&value=' + checkedRooms + '&url=' + url,
  397.        dataType: "json",
  398.        success: function (response) {
  399.            update_apartments_html(response);
  400.        }
  401.    });
  402. });
  403.  
  404.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement