/*! * Filter Everything set admin 1.9.7 */ (function($) { "use strict"; let filtersFormValid = false; let postTypesTaxList = wpcSetVars.postTypesTaxList; let numFieldNoTaxes = wpcSetVars.numFieldNoTaxes; let numFieldAttrs = wpcSetVars.numFieldAttrs; let isLimitFilterSet = wpcSetVars.isLimitFilterSet; function validateFiltersForm( $el ) { let $spinner = $('#publishing-action .spinner'); let requestParams = {}; const keepFields = [ '_wpnonce', '_flrt_nonce', '_wp_http_referer', 'user_ID', 'action', 'originalaction', 'post_author', 'post_type', 'original_post_status', 'post_ID', 'post_title', 'save', 'post_status', 'wpc_filter_set_json_data', ]; $spinner.addClass( 'is-active' ); /** * @todo checkboxes does not validates correctly because they send the same value !!! IMPORTANT * independently from checked status */ requestParams.validateData = JSON.stringify(wpcSerialize( $el )); wp.ajax.post( 'wpc-validate-filters', requestParams ) .always( function() { $spinner.removeClass( 'is-active' ); }) .done( function( response ) { filtersFormValid = true; const wpcHiddenInput = document.createElement('input'); wpcHiddenInput.type = 'hidden'; wpcHiddenInput.name = 'wpc_filter_set_json_data'; wpcHiddenInput.value = JSON.stringify(wpcSerialize( $el )); $el.append(wpcHiddenInput); // Find the elements that need to be "disabled" const $toDisable = $el.find('[name]').not(keepFields.map(n => `[name="${n}"]`).join(',')); // Save name and remove before submit $toDisable.each(function() { $(this).attr('data-name', $(this).attr('name')).removeAttr('name'); }); $el.submit(); // Restore name after submit $toDisable.each(function() { $(this).attr('name', $(this).attr('data-name')).removeAttr('data-name'); }); }) .fail( function( response ) { let notices = []; let filterContainer = ''; if( typeof response.errors !== 'undefined' ){ $.each( response.errors, function ( index, error ){ if( typeof error.id !== 'undefined'){ addFieldError( error.id, error.message ); // Open filter container to show error filterContainer = $('#'+error.id).parents('.wpc-filter-item'); openFilter(filterContainer); // Open additional fields if errors are there if( $('#'+error.id).parents('.wpc-filter-additional-fields').length > 0 ){ openAdditional(filterContainer); } }else{ notices.push( error.message ); } }); if( notices.length < 1 ){ notices.push( 'Error: Set was not saved.' ); } addNotice( notices ); } }); return false; } function removeElement($el) { $el.fadeTo(100, 0, function() { $el.slideUp(100, function() { $el.remove(); }); }); } function addFieldError( fieldId, message ) { let target = $('#'+fieldId); let html = '

'+message+'

'; if( typeof target !== 'undefined' ){ target.before( html ); } } function addNotice( messages ) { let target = $('form#post'); let text = ''; $.each( messages, function ( index, message ) { text += '

' + message + '

'; }); let html = '
' + text + '' + '
'; if( typeof target !== 'undefined' ){ if( $("#message").length > 0 ){ $("#message").remove(); } target.before( html ); } } function openFilter($el) { let head = $el.find('.wpc-filter-head'), body = head.next('.wpc-filter-body'); head.addClass('wpc-opened'); body.slideDown({ duration: 200, complete: function (){ body.addClass('wpc-opened'); } }); } function closeFilter($el) { let head = $el.find('.wpc-filter-head'), body = head.next('.wpc-filter-body'); head.removeClass('wpc-opened'); body.slideUp({ duration: 200, complete: function (){ body.removeClass('wpc-opened'); } }); } function closeAdditional($el) { $el.find('.wpc-filter-additional-fields').slideUp({ duration: 200, complete: function (){ $(this).removeClass('wpc-opened'); } }); } function openAdditional($el) { $el.find('.wpc-filter-additional-fields').slideDown({ duration: 200, complete: function (){ $(this).addClass('wpc-opened'); } }); } /** * Creates array with taxonomies that do not belong to the Post type * selected in Filter Set * @returns {[]|*[]} */ function getForbiddenTaxes() { if( typeof wpcSetVars.postTypesTaxList !== 'undefined'){ let postType = $('#wpc_set_fields-post_type').val(); let allowedTaxes = []; let forbiddenTaxes = []; if( typeof wpcSetVars.postTypesTaxList[postType] !== 'undefined' ){ $.each( wpcSetVars.postTypesTaxList[postType], function ( iNdex, taxProps ){ allowedTaxes.push(taxProps['name']); }); } $.each( wpcSetVars.postTypesTaxList, function ( pType, taxesArray ){ if( pType !== postType ){ $.each( taxesArray, function ( index, theTax ){ if( allowedTaxes.includes(theTax['name']) === false ){ forbiddenTaxes.push(theTax['name']); } } ) } }); return forbiddenTaxes; } return []; } /** * Retrieves already selected filter entities to disable double using of them * @param $inputs - select tags, where we collect used entities. Usually .wpc-field-entity * @param excludeInput * @returns {boolean|[]} */ function getUsedEntities( $inputs, excludeInput ) { let usedEntities = []; let currentVal = ''; // Pass through these entities let doNotInclude = ['post_meta', 'post_meta_num', 'post_meta_exists', 'tax_numeric', 'post_meta_date']; if ( $inputs.length > 0 ) { $inputs.each( function(){ currentVal = $(this).val(); // Continue if( $(this).attr('id') == excludeInput.attr('id') ){ return; } if( doNotInclude.includes( currentVal ) ){ return; } if( currentVal ) { usedEntities.push( currentVal ); } }); return usedEntities; } return false; } /** * Pass through new filter entity options and set as disabled already used taxonomies * @param $theSelect - the select element with options to set. Usually it is .wpc-field-entity * @param dropdownClass - class of the select element where we have to set option status * @param noChange * @returns {boolean} */ function setAvailableEntities( $theSelect, noChange ) { // .wpc-field-entity let currentVal = ''; let selectClass = $theSelect.attr('class'); const excludeRaw = getUsedEntities( $( '.'+selectClass ), $theSelect ); const exclude = Array.isArray(excludeRaw) ? excludeRaw : []; let forbiddenTaxes = getForbiddenTaxes(); // $theSelect.find('option').each( function (){ currentVal = $(this).val(); if( currentVal === 'post_meta_exists' && ( wpcSetVars.filtersPro < 1 ) ) { return; } if( currentVal === 'tax_numeric' && ( wpcSetVars.filtersPro < 1 ) ) { return; } if( exclude.includes( currentVal ) || forbiddenTaxes.includes( currentVal ) ){ $(this).attr( 'disabled', 'disabled' ); }else{ $(this).removeAttr( 'disabled' ); } } ); // If currently selected option is disabled, make first available option selected. let disabled = $theSelect.find('option:selected').attr('disabled'); // if noChange === false this works if( disabled === 'disabled' && ! noChange ){ $theSelect.find('option:not([disabled]):first').prop('selected', true) .trigger('change'); } return true; } function handleShowTerms( select ) { let currentVal = select.val(); let currentFid = select.parents('.wpc-filter-item').data('fid'); currentVal = wpcShortenEname( currentVal ); let $formTable = $( "#wpc-filter-id-"+currentFid+" .wpc-form-fields-table" ); if ( wpcSetVars.swatchesTaxonomies.includes( currentVal ) ){ $formTable.addClass("taxonomy-has-swatches"); } else { $formTable.removeClass("taxonomy-has-swatches"); } if ( wpcSetVars.brandEntities.includes( currentVal ) ){ $formTable.addClass("wpc-filter-has-brands"); } else { $formTable.removeClass("wpc-filter-has-brands"); } if ( wpcSetVars.ratingTaxonomies.includes( currentVal ) ){ $formTable.addClass("selected-and-above-show"); } else { $formTable.removeClass("selected-and-above-show"); } } function passNewEntities( select ) { let time = 0; $('.wpc-new-filter-item .wpc-field-entity').each( function () { let select = $(this); let noChange = false; // Do not change current select tag if( $(this).attr('id') == select.attr('id') ) { noChange = true; } setTimeout( function(){ setAvailableEntities( select, noChange ); }, time); time += 100; }); } $.fn.getCursorPosition = function() { var input = this.get(0); if (!input) return; // No (input) element found if ('selectionStart' in input) { // Standard-compliant browsers return input.selectionStart; } else if (document.selection) { // IE input.focus(); var sel = document.selection.createRange(); var selLen = document.selection.createRange().text.length; sel.moveStart('character', -input.value.length); return sel.text.length - selLen; } } $(document).ready(function (){ $('form#post').on('submit', function(e){ // Clear all errors removeElement( $('.wpc-field-notice') ); // Clear Notice removeElement( $('#message') ); // Close All Filters closeFilter( $(".wpc-filter-item") ); if( ! filtersFormValid ){ e.preventDefault(); // Validate form. We will submit it from validation method validateFiltersForm($(this)); } }); $('.wpc-add-filter').on('click', function (e){ e.preventDefault(); let html = $('#wpc-new-filter').html(); let $el = $(html); let search = 'wpc_new_id'; let replace = uniqId('filter_'); let replaceAttr = function(i, value){ return value.replace( search, replace ); } let filtersListContainer = $('#wpc-filters-list'); $el.find('[id*="' + search + '"]').attr('id', replaceAttr); $el.find('[for*="' + search + '"]').attr('for', replaceAttr); $el.find('[name*="' + search + '"]').attr('name', replaceAttr); $el.find('[class*="' + search + '"]').attr('class', replaceAttr); $el.data('fid', replace); $el.attr('id', 'wpc-filter-id-'+replace); let latestElem = $(".wpc-filter-item").last(); if ( latestElem.hasClass('wpc-filter-not-listed') ) { let prevLatestElem = latestElem.prev('.wpc-filter-item'); if ( prevLatestElem.hasClass('wpc-filter-not-listed') ) { prevLatestElem.before($el); } else { latestElem.before($el); } } else { filtersListContainer.append($el); } let select = $el.find('.wpc-field-entity'); syncEntityWithPrefix(select); handleMetaKeyField(select); setEntityTableClass(select); syncEntityWithView(select); syncEntityWithSortTerms(select); // Make already used entities unavailable to selection setAvailableEntities( select ); handleHierarchyField( select ); handleShowTerms( select ); // handleUsedForVariationsField( select ); $el.find('.wpc-field-exclude').select2({ width: '100%', placeholder: wpcSetVars.excludePlaceholder, }); // Fire this event to load exclude terms for first filter if( $(".wpc-filter-item:not(.wpc-filter-not-listed)").length === 1 ){ select.trigger('change'); } $('.wpc-help-tip').tipTip({ 'attribute': 'data-tip', 'fadeIn': 50, 'fadeOut': 50, 'delay': 200, 'keepAlive': true, 'maxWidth': "220px", }); openFilter($el); renderMenuOrder(); handleNoFiltersMessage(); // Update Parent filter dropdown wpcAddNewFilterToParentList(); /** * @todo There is problem with down arrow when we adding new filter !!! IMPORTANT */ }); $('.wpc-form-fields-table:not(.wpc-filter-tax_numeric) .wpc-field-exclude, .wpc-form-fields-table:not(.wpc-filter-post_meta_num) .wpc-field-exclude, .wpc-form-fields-table:not(.wpc-filter-post_meta_exists) .wpc-field-exclude').select2({ width: '100%', placeholder: wpcSetVars.excludePlaceholder }); $('body').on('click', '.notice-dismiss', function(e){ e.preventDefault(); removeElement( $('#message') ); }); // Show delete buttons $('body').on('click', '.wpc-button-link-delete', function(e){ e.preventDefault(); $(this).parents('.wpc-filter-label-td') .next('.wpc-filter-field-td') .children('.wpc-filter-delete-wrapper').css('visibility', 'visible'); }); $('body').on('click', '.wpc-filter-delete-cancel', function(e){ e.preventDefault(); removeElement( $('.wpc-field-notice') ); $(this).parents('.wpc-filter-delete-wrapper').css('visibility', 'hidden'); }); $('body').on('click', '.wpc-done-action', function(e){ $(this).parents('.wpc-filter-body').slideToggle(200) .toggleClass('wpc-opened') .children('.wpc-filter-additional-fields').removeClass('wpc-additional-opened') .hide(); $(this).parents('.wpc-filter-body').prev('.wpc-filter-head').toggleClass('wpc-opened'); // Hide delete buttons $(this).parents('.wpc-filter-field-td') .next('.wpc-filter-field-td') .find('.wpc-filter-delete-wrapper').css('visibility', 'hidden'); }); $('body').on('click', '.wpc-advice-head', function(e){ // let body = $(this).next('.wpc-advice-body'); $(this).toggleClass('wpc-opened'); // body.slideToggle(200) // body.toggle(200) // body.toggleClass('wpc-opened'); }); $('body').on('click', '.wpc-title-action', function(e){ let head = $(this).parent('.wpc-filter-head'), body = head.next('.wpc-filter-body'); head.toggleClass('wpc-opened'); body.slideToggle(200) .toggleClass('wpc-opened') .children('.wpc-filter-additional-fields').removeClass('wpc-additional-opened') .hide(); body.find('.wpc-filter-delete-wrapper').css('visibility', 'hidden'); let moreOptions = body.find('.wpc-more-options-toggle'); if( moreOptions.hasClass('wpc-opened') ){ moreOptions.trigger('click'); } }); $('body').on('click', '.wpc-more-options-toggle', function(e){ e.preventDefault(); let moreText = $(this).text(); if( moreText === wpcSetVars.moreOptions ){ $(this).text( wpcSetVars.lessOptions); }else{ $(this).text( wpcSetVars.moreOptions); } $(this).toggleClass('wpc-opened'); $(this).parents('.wpc-filter-body').find('.wpc-filter-additional-fields').slideToggle(200) .toggleClass('wpc-additional-opened'); }); $('body').on('change', 'select.wpc-field-ename', function(e){ let time = 0; // let fid = $(this).parents('.wpc-filter-item').data('fid'); $( $('.wpc-new-filter-item select.wpc-field-ename').get().reverse() ).each( function () { let eNameSelect = $(this); setTimeout( function(){ setAvailableEntities( eNameSelect, false ); }, time); time += 100; }); }); $('body').on('change', '.wpc-field-entity', function(e){ let thisSelect = $(this); let theTitle = ''; // Set available entities again passNewEntities(thisSelect); syncEntityWithPrefix(thisSelect); handleMetaKeyField(thisSelect); handleLogicField(thisSelect); setEntityTableClass(thisSelect); syncEntityWithView(thisSelect); syncEntityWithSortTerms(thisSelect); handleHierarchyField(thisSelect); handleShowTerms( thisSelect ); // handleUsedForVariationsField(select); // Load terms for exclude let entity = $(this).val(); let fid = $(this).parents('.wpc-filter-item').data('fid'); if ( entity === 'tax_numeric' ) { $('#wpc_filter_fields-'+fid+'-e_name').trigger('change'); } // replace with includes if ( [ 'tax_numeric', 'post_meta', 'post_meta_num', 'post_meta_exists', 'post_date', 'post_meta_date' ].includes(entity) ) { let target = $('#wpc_filter_fields-'+fid+'-exclude'); target.select2({ disabled: true, width: '100%' }); }else{ loadExcludeItems(entity, fid); } let entityLabel = $(this).find('option:selected').text(); let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-entity'); target.text(entityLabel); theTitle = $("#wpc_filter_fields-"+fid+"-label").val(); if( ! theTitle ){ theTitle = wpcSetVars.newFilter; } $(".wpc-field-parent-filter option[value='"+fid+"'").each(function (index, element){ $(this).text( theTitle + " (" +wpcShortenEname( entity )+ ")" ); if( entity === 'post_meta_num' || entity === 'tax_numeric' || entity === 'taxonomy_product_visibility' ){ $(this).attr('disabled', 'disabled'); }else{ $(this).removeAttr('disabled'); } }); }); // Try to prepend slug if it already exists $('body').on('input change', '.wpc-field-ename', function(){ let ename = $(this).val(); let fid = $(this).parents('.wpc-filter-item').data('fid'); let entity = $('#wpc_filter_fields-'+fid+'-entity').val(); let val = ''; let slugs = wpcSetVars.filterSlugs; if ( entity === 'post_meta_num' ) { val = 'post_meta_num_' + ename; } else if ( entity === 'tax_numeric' ) { val = 'tax_numeric_' + ename; } else if ( entity === 'post_meta_exists' ) { val = 'post_meta_exists_' + ename; } else if ( entity === 'post_meta_date' ) { val = 'post_meta_date_' + ename; }else { val = 'post_meta_' + ename; } if( typeof slugs[val] !== 'undefined' ){ $('#wpc_filter_fields-'+fid+'-slug').val( slugs[val] ) .trigger('input'); // Do not load exclude terms for Post Meta Num and Tax Numeric if( entity !== 'post_meta_num' && entity !== 'tax_numeric'){ loadExcludeItems(entity, fid, ename); } }else{ $('#wpc_filter_fields-'+fid+'-slug').val('') .trigger('input'); $('#wpc_filter_fields-'+fid+'-exclude').select2({ disabled: true, width: '100%', }); } }); $('body').on('input', '.wpc-field-value-step', function (){ $(this).val( $(this).val().replace(/,/g, '.') ); $(this).val( $(this).val().replace(/[^\d\.]/g, '') ); }); $('body').on('input keydown', '#wpc_set_fields-apply_button_text', function (){ let target = $("#wpc-filter-id-apply-button").find('.wpc-button-apply'); cpaLiveWrite( $(this), target ); }); $('body').on('input keydown', '#wpc_set_fields-reset_button_text', function (){ let target = $("#wpc-filter-id-apply-button").find('.wpc-button-reset'); cpaLiveWrite( $(this), target ); }); $('body').on('input keydown', '#wpc_set_fields-search_field_placeholder', function (){ let target = $("#wpc-filter-id-search-field").find('.wpc-text-input-search'); target.attr('placeholder', $(this).val()); }); $('body').on('input keydown', '#wpc_set_fields-search_field_label', function (){ let target = $("#wpc-filter-id-search-field").find('.wpc-filter-label'); cpaLiveWrite( $(this), target ); // target.attr('placeholder', $(this).val()); }); $('body').on('input keydown', '.wpc-field-slug', function (){ let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-slug'); cpaLiveWrite( $(this), target ); }); $('body').on('input keydown', '.wpc-field-label', function (){ let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-label'); cpaLiveWrite( $(this), target ); let fid = $(this).parents(".wpc-filter-item").data('fid'); let eName = $("#wpc_filter_fields-"+fid+"-entity").val(); eName = wpcShortenEname( eName ); let theTitle = $(this).val(); $(".wpc-field-parent-filter option[value='"+fid+"'").each(function (index, element){ $(this).text( theTitle + " (" + eName + ")" ); }); }); $('body').on('change', '.wpc-field-show-range-list', function (){ let rangeListButtonChecked = $(this).prop( "checked" ); if( rangeListButtonChecked ){ $(".wpc-view-range").addClass('wpc-view-range-list'); }else{ $(".wpc-view-range").removeClass('wpc-view-range-list'); } }); $('body').on('change', '.wpc-field-view', function(){ const $this = $(this); const $option = $this.find('option:selected'); const optionName = $option.text(); const optionVal = $option.val(); const $divFilterItem = $this.parents('.wpc-filter-item'); // Update View Label in Header $divFilterItem.find('.wpc-filter-head li.wpc-filter-view').text(optionName); // Handle visibility of Search and More/Less fields const allowedViews = ['checkboxes', 'radio', 'labels']; const showExtraFields = allowedViews.includes(optionVal); $divFilterItem.find('.wpc-field-search-tr, .wpc-field-more-less-tr').toggle(showExtraFields); // Handle CSS classes for the fields table const $fieldsTable = $divFilterItem.find('.wpc-form-fields-table'); const classesToRemove = 'wpc-view-checkboxes wpc-view-dropdown wpc-view-rating wpc-view-range selected-and-above-show'; // Map option values to their specific CSS classes const viewClasses = { 'checkboxes': 'wpc-view-checkboxes', 'rating': 'wpc-view-rating', 'range': 'wpc-view-range', 'dropdown': 'wpc-view-dropdown' }; // Reset classes first $fieldsTable.removeClass(classesToRemove); // Add specific class if exists in map if (viewClasses[optionVal]) { $fieldsTable.addClass(viewClasses[optionVal]); } // Handle special case for 'rating' if (optionVal === 'rating') { $fieldsTable.addClass('selected-and-above-show'); } }); $( '.wpc-filter-set-wrapper .wpc-filters-list' ).sortable({ items: "> div.wpc-filter-item", delay: 150, placeholder: "wpc-filter-item-shadow", refreshPositions: true, cursor: 'move', handle: ".wpc-filter-order", axis: 'y', update: function( event, ui ) { renderMenuOrder(); }, start: function ( event, ui ){ let head = ui.item.children('.wpc-filter-head'), inside = ui.item.children('.wpc-filter-body'); if ( inside.hasClass('wpc-opened') ) { inside.removeClass('wpc-opened') .hide(); head.removeClass('wpc-opened'); $(this).sortable('refreshPositions'); } $('.wpc-filter-item-shadow').css('min-height', head.height() + 'px'); } }); $('.wpc-filter-set-wrapper .wpc-filters-list').keydown(function(e){ if (e.keyCode == 65 && (e.ctrlKey || e.metaKey) ) { e.target.select() } }) $( ".wpc-filters-list" ).disableSelection(); // Deleter filter $('body').on('click', '.wpc-filter-delete', function (){ removeElement( $('.wpc-field-notice') ); let $spinner = $(this).prev('.spinner'); $spinner.addClass( 'is-active' ); let requestParams = {}; requestParams._wpnonce = $("#wpc_set_nonce").val(); requestParams.fid = $(this).data('fid'); // @feature localize this var if( requestParams.fid === 'wpc_new_id' ){ let $filterItem = $(this).parents('.wpc-filter-item'); $filterItem.slideUp({ duration: 200, complete: function (){ $(this).remove(); renderMenuOrder(); handleNoFiltersMessage(); } }) } // Remove current filter from Parent filters list let dataFid = $(this).parents('.wpc-filter-item').data('fid'); wpcDeleteFilterFromParentList( dataFid ); wp.ajax.post( 'wpc-delete-filter', requestParams ) .always( function() { $spinner.removeClass( 'is-active' ); }) .done( function( response ) { if( typeof response !== 'undefined' && typeof response.fid !== 'undefined' ){ $("#wpc-filter-id-"+response.fid).slideUp({ duration: 200, complete: function (){ $(this).remove(); renderMenuOrder(); handleNoFiltersMessage(); // Set available entities again // @todo doesn't work properly if there are several new filters exists on a page !!! IMPORTANT // doesn't make some entities available, but should. passNewEntities(); } }) } }) .fail( function(response) { if( typeof response !== 'undefined'){ addFieldError( 'wpc-filter-delete-wrapper-'+response.fid, response.message ); } }); }); // Get set location fields let selected_link = $('#wpc_set_fields-post_type option:selected').data('link'); if(selected_link != ''){ $('.wpc-location-preview-not-pro').removeClass('display-none'); } $('body').on('change', '#wpc_set_fields-post_type', function (){ let postType = $(this).val(); $("#wpc-filters-list").attr('data-posttype', postType ); let link = $('option:selected', this).data('link'); $('.wpc-location-preview-not-pro').attr('href', link); if(link != ''){ $('.wpc-location-preview-not-pro').removeClass('display-none'); }else{ $('.wpc-location-preview-not-pro').addClass('display-none'); } setAvailableEntities( $('.wpc-new-filter-item .wpc-field-entity') ); removeElement( $('.wpc-field-notice') ); // Update Post type related location terms let selected = $('#wpc_set_fields-wp_page_type').val(); if( typeof selected !== 'undefined' /*&& selected === 'common:common'*/ ){ wpcGetLocationTerms( selected ); } let selectEntity = $("select.wpc-field-entity"); const postMetaValues = ['post_meta', 'post_meta_num', 'post_meta_exists', 'post_meta_date']; // Change options in all select.wpc-field-ename let eNameSelect = $("select.wpc-field-ename"); if(postMetaValues.includes(selectEntity.val())){ handleMetaKeyField(selectEntity); return; } if( eNameSelect.length > 0 ) { fillTaxNumSelect( eNameSelect, postType ); } }); // Filtered WP_Query location $('body').on('change', '#wpc_set_fields-wp_page_type', function(){ wpcGetLocationTerms( $(this).val() ); }); // Apply button location $('body').on('change', '#wpc_set_fields-apply_button_page_type', function(){ wpcGetApplyLocationTerms( $(this).val() ); }); $('body').on('change', '#wpc_set_fields-post_name', function (e){ let filterPagelink = $('option:selected', this).data('link'); if( typeof filterPagelink !== 'undefined'){ wpcGetWpQueries( filterPagelink ); } }); $('body').on( 'change', '.wpc-date-format', function (e){ let otherFieldName = $(this).attr('name'); let $customField = $( '.wpc-date-custom-format[name="'+otherFieldName+'"]' ); if ( $(this).attr('value') === 'other' ) { $customField.removeAttr('disabled'); } else { $customField.val( $(this).val() ); $customField.attr('disabled', 'disabled'); } }); $('body').on('change', '.wpc-date-type', function (e){ let dataFid = $(this).parents('.wpc-filter-item').data('fid'); let $spinner = $( '.wpc_filter_fields-'+dataFid+'-date_format-wrap' ).children( '.spinner' ); $spinner.addClass( 'is-active' ); // Set up AJAX request let requestParams = {}; //requestParams._wpnonce = $("#wpc_set_nonce").val(); requestParams.setId = $("#post_ID").val(); requestParams.dateType = $("#wpc_filter_fields-"+dataFid+"-date_type").val(); requestParams.fid = dataFid; wp.ajax.post( 'wpc_get_date_formats', requestParams ) .always( function() { $spinner.removeClass( 'is-active' ); }) .done( function( response ) { if ( typeof response.html !== 'undefined' ) { let setDefault = true; let radioList = $(response.html).find('ul'); $.each( radioList.find('input.wpc-date-format'), function( key, value ){ let theOption = $(this); if( theOption.is(':checked') ){ setDefault = false; return; } }); if( setDefault === true ) { radioList.find('input.wpc-date-format:first').attr('checked', 'checked'); } $( '.wpc_filter_fields-'+dataFid+'-date_format-wrap ul' ).replaceWith(radioList); } }) .fail( function(response) { // {"success":false} }); }); $('body').on('change', '.wpc-field-parent-filter', function (){ let parentNo = ['no', '-1']; let parentVal = $(this).val(); let fid = $(this).parents('.wpc-filter-item').data('fid'); let hideTr = $("#wpc-filter-id-"+fid+" .wpc-field-hide-until-parent-tr"); if( parentNo.includes(parentVal) ){ hideTr.removeClass('wpc-opened'); }else{ hideTr.addClass('wpc-opened'); } }); $('body').on('click', '#wpc_set_fields-use_apply_button', function (){ let applyButtonChecked = $(this).prop( "checked" ); if( applyButtonChecked ){ $("#wpc-filter-id-apply-button").addClass('wpc-opened'); $(".wpc-field-apply-button-text-tr").addClass('wpc-opened'); $(".wpc-field-apply-button-page-type-tr").addClass('wpc-opened'); $(".wpc-field-reset-button-text-tr").addClass('wpc-opened'); $('.wpc-no-filters').hide(); }else{ $("#wpc-filter-id-apply-button").removeClass('wpc-opened'); $(".wpc-field-apply-button-text-tr").removeClass('wpc-opened'); $(".wpc-field-apply-button-page-type-tr").removeClass('wpc-opened'); $(".wpc-field-reset-button-text-tr").removeClass('wpc-opened'); if( $(".wpc-filter-item:visible").length < 1 ){ $('.wpc-no-filters').show(); } } }); $('body').on('click', '#wpc_set_fields-horizontal_view', function (){ let applyButtonChecked = $(this).prop( "checked" ); $("#wpc_set_fields-horizontal_view_priority").val('filter_set'); if( applyButtonChecked ){ $(".wpc-field-horizontal-view-column-tr").addClass('wpc-opened'); }else{ $(".wpc-field-horizontal-view-column-tr").removeClass('wpc-opened'); } }); $('body').on('click', '#wpc_set_fields-use_search_field', function (){ let searchFieldChecked = $(this).prop( "checked" ); if( searchFieldChecked ){ $("#wpc-filter-id-search-field").addClass('wpc-opened'); $(".wpc-search-field-placeholder-tr").addClass('wpc-opened'); $(".wpc-search-field-label-tr").addClass('wpc-opened'); $('.wpc-no-filters').hide(); }else{ $("#wpc-filter-id-search-field").removeClass('wpc-opened'); $(".wpc-search-field-placeholder-tr").removeClass('wpc-opened'); $(".wpc-search-field-label-tr").removeClass('wpc-opened'); if( $(".wpc-filter-item:visible").length < 1 ){ $('.wpc-no-filters').show(); } } }); $('body').on('focus keypress blur', '.wpc-field-min-num-label, .wpc-field-max-num-label', function (e){ let wpcPosition = $(this).getCursorPosition(); $(this).data('caret', wpcPosition); }); $('body').on('click', '.wpc-variable-inserter', function (e){ let wrapper = $(this).parents('.wpc-filter-field-min-max-labels-wrap'); $.each( wrapper.find('input[type="text"]'), function( i, field ){ let inputField = $( field ); let valueVar = '{value}'; let caretPos = inputField.data('caret'); if( caretPos === 0 ){ valueVar = valueVar+' '; }else if( caretPos === inputField.val().length ){ valueVar = ' '+valueVar; }else{ // Undefined or position in the end valueVar = ' '+valueVar+' '; } insertAtCaret( inputField, valueVar, caretPos ); } ); }); let filterPagelink = $('option:selected', $('#wpc_set_fields-post_name')).data('link'); $('.wpc-location-preview').addClass('display-none'); if( typeof filterPagelink !== 'undefined' && filterPagelink ){ $('.wpc-location-preview').removeClass('display-none'); wpcGetWpQueries( filterPagelink ); } let notProFilterPagelink = $('option:selected', $('#wpc_set_fields-post_type')).data('link'); if( typeof notProFilterPagelink !== 'undefined' && notProFilterPagelink ){ $('.wpc-location-preview-not-pro').attr('href', notProFilterPagelink); $('.wpc-location-preview-not-pro').removeClass('display-none'); } }); $('body').on('click', '.wpc-field-show-range-list-input', function (e){ e.preventDefault(); let $prevRow = $(this).prev('.range-list-value'); const $currentRangeValues = $(this) .parent() .find('.range-list-value'); if($('.wpc-range-list-value-error-button').length > 0){ $('.wpc-range-list-value-error-button').remove(); } if($prevRow.length > 0 && $prevRow.find('.wpc-range-list-min-value').val() === '' && $prevRow.find('.wpc-range-list-max-value').val() === ''){ let error_html = `
${wpcSetVars.rangeListTexts.error}
`; $(this).after(error_html); return false; } const name = $(this).attr('name'); let lastRangeListNumber = 1; if ($currentRangeValues.length) { lastRangeListNumber = Math.max( ...$currentRangeValues.map(function () { return Number($(this).data('list-number')) || 0; }).get() ) + 1; } let html = `
`; $(this).before(html); if(wpcSetVars.limitForRangeList <= $(this).parent().find('.range-list-value').length){ $(this).prop('disabled', true); return false; } changeRangeListInputStatus(); }); $(document).on('keyup change mouseup', '.wpc-range-list-min-value, .wpc-range-list-max-value', function (e){ let $currentRow = $(this).parents('.range-list-value'); let $rangeListMin = $currentRow.find('.wpc-range-list-min-value'); let $rangeListMax = $currentRow.find('.wpc-range-list-max-value'); let rangeListTextVal = ''; let $prevRow = $currentRow.prev('.range-list-value'); let rangeMinVal = $rangeListMin.val(); let rangeMaxVal = $rangeListMax.val(); if ($rangeListMin.val() === '') { rangeMinVal = wpcSetVars.rangeListTexts.up_to; } if ($rangeListMax.val() === '') { rangeMaxVal = wpcSetVars.rangeListTexts.and_up; } if ($prevRow.length > 0) { if ($prevRow.find('.wpc-range-list-max-value').val() !== '' && $prevRow.find('.wpc-range-list-max-value').val() !== 0) { if(typeof $rangeListMin.val() !== 'undefined'){ rangeMinVal = $prevRow.find('.wpc-range-list-max-value').val(); if (e.type === 'change' && $rangeListMin.val() === '' && parseFloat(rangeMinVal) <= parseFloat($rangeListMax.val())) { $rangeListMin.val(rangeMinVal); } } } } if($rangeListMin.val() !== '') { rangeMinVal = $rangeListMin.val(); } if($rangeListMin.val() === '' && parseFloat(rangeMinVal) >= parseFloat($rangeListMax.val())){ rangeMinVal = wpcSetVars.rangeListTexts.up_to; } if(typeof rangeMinVal === 'undefined'){ rangeMinVal = wpcSetVars.rangeListTexts.up_to; } rangeListTextVal += rangeMinVal + ' - ' + rangeMaxVal; if($rangeListMin.val() === '' && $rangeListMax.val() === '' ) { rangeListTextVal = ''; }else{ if($currentRow.find('.wpc-range-list-value-error').length > 0){ $currentRow.find('.wpc-range-list-value-error').remove(); } } if($('.wpc-range-list-value-error-button').length > 0){ $('.wpc-range-list-value-error-button').remove(); } if(e.type === 'change'){ if ($rangeListMin.val() != '' && $rangeListMax.val() != '' && parseFloat($rangeListMin.val()) >= parseFloat($rangeListMax.val())) { let html_val_error = `
${wpcSetVars.rangeListTexts.value_error}
`; $currentRow.append(html_val_error); } } $currentRow.find('.wpc-range-list-range-text').val(rangeListTextVal); }); $(document).on('click', '.remove-range-list-value', function (e){ e.preventDefault(); $(this).parents('.range-list-value').remove(); if($('.range-list-value').length < wpcSetVars.limitForRangeList && $('.wpc-field-show-range-list-input').is(':disabled')){ $('.wpc-field-show-range-list-input').removeAttr('disabled'); } if($('.wpc-range-list-value-error-button').length > 0){ $('.wpc-range-list-value-error-button').remove(); } changeRangeListInputStatus(); }); function changeRangeListInputStatus(){ let $rangeListValues = $('.wpc-field-show-range-list-input-tr').find('.range-list-value'); $rangeListValues.removeClass('wpc-is-first-range-list-value wpc-is-last-range-list-value'); $rangeListValues.first().addClass('wpc-is-first-range-list-value'); $rangeListValues.last().addClass('wpc-is-last-range-list-value'); /* if(!$rangeListValues.last().hasClass('wpc-is-first-range-list-value')){ $rangeListValues.last().addClass('wpc-is-last-range-list-value'); }*/ } function wpcShortenEname( eName ){ let shortenName = eName; if( eName.includes( 'taxonomy_' ) ){ if( eName.slice(0, 9) === 'taxonomy_' ){ shortenName = eName.slice(9); } }else if( eName.includes( 'author_' ) ){ if( eName.slice(0, 7) === 'author_' ){ shortenName = eName.slice(7); } } return shortenName; } function wpcAddNewFilterToParentList(){ let allIds = {}; let theFid = 0; let theTitle = '' let theEname = ''; let theNoVal = false; let possibleOption = false; let newOption = false; $(".wpc-filter-item:not(.wpc-filter-not-listed)").each( function ( index, elem ){ theFid = $(this).data('fid'); theTitle = $("#wpc_filter_fields-"+theFid+"-label").val(); if( ! theTitle ){ theTitle = wpcSetVars.newFilter; } theEname = $("#wpc_filter_fields-"+theFid+"-entity").val(); // theEname = wpcShortenEname(theEname); allIds[theFid] = { 'id' : theFid.toString(), 'title': theTitle, 'ename': theEname}; } ); // In case if there is only single filter in Set if( Object.keys(allIds).length < 2 ){ //console.log('Less than 2'); return; } // If there are 2 or more filters $.each( allIds, function ( index, elem ){ theNoVal = $( "#wpc_filter_fields-"+elem['id']+"-parent_filter > option[value='no']"); if( theNoVal.length > 0 ){ theNoVal.val( '-1' ); theNoVal.text( wpcSetVars.selectFilter ); } $.each( allIds, function ( inindex, inelem ){ if( elem['id'] === inindex ){ return; } possibleOption = $( "#wpc_filter_fields-"+elem['id']+"-parent_filter > option[value='"+inindex+"']"); if( possibleOption.length < 1 ){ newOption = $('