/**
* HVAC Trainer Dashboard JavaScript
*
* Handles dynamic filtering of events table and other interactive features.
*/
(function($) {
'use strict';
// Initialize the dashboard when DOM is ready
$(document).ready(function() {
initEventFilters();
});
/**
* Initialize event filters to work without page reload
*/
function initEventFilters() {
// Get the events table wrapper element
const $eventsTableWrapper = $('.hvac-events-table-wrapper');
// Add click handler to filter links
$('.hvac-event-filters a').on('click', function(e) {
e.preventDefault(); // Prevent default link behavior (page reload)
// Get the status filter from the link URL
const url = new URL($(this).attr('href'), window.location.origin);
const status = url.searchParams.get('event_status') || 'all';
// Update active class
$('.hvac-event-filters a').removeClass('hvac-filter-active ast-button-primary').addClass('ast-button-secondary');
$(this).addClass('hvac-filter-active ast-button-primary').removeClass('ast-button-secondary');
// Show loading indicator
$eventsTableWrapper.append('
Filtering events...
');
// Make AJAX request to get filtered events
$.ajax({
url: hvac_dashboard.ajax_url,
type: 'POST',
data: {
action: 'hvac_filter_events',
status: status,
nonce: hvac_dashboard.nonce
},
success: function(response) {
if (response.success) {
// Replace the table HTML with the filtered results
$eventsTableWrapper.html(response.data.html);
// Update the URL without reloading the page
if (history.pushState) {
const newUrl = status === 'all'
? removeURLParameter(window.location.href, 'event_status')
: addURLParameter(window.location.href, 'event_status', status);
window.history.pushState({ path: newUrl }, '', newUrl);
}
} else {
// Show error message
$eventsTableWrapper.find('.hvac-loading').remove();
$eventsTableWrapper.append('Error loading events: ' + response.data.message + '
');
}
},
error: function() {
// Show error message
$eventsTableWrapper.find('.hvac-loading').remove();
$eventsTableWrapper.append('Error communicating with server.
');
}
});
});
}
/**
* Helper function to add a URL parameter
*/
function addURLParameter(url, key, value) {
const re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
const separator = url.indexOf('?') !== -1 ? "&" : "?";
if (url.match(re)) {
return url.replace(re, '$1' + key + "=" + value + '$2');
} else {
return url + separator + key + "=" + value;
}
}
/**
* Helper function to remove a URL parameter
*/
function removeURLParameter(url, parameter) {
const urlParts = url.split('?');
if (urlParts.length < 2) {
return url;
}
const urlBase = urlParts[0];
const queryString = urlParts[1];
const prefix = encodeURIComponent(parameter) + '=';
const parts = queryString.split(/[&;]/g);
// Reverse iteration to safely remove items
for (let i = parts.length; i-- > 0;) {
if (parts[i].lastIndexOf(prefix, 0) !== -1) {
parts.splice(i, 1);
}
}
const newQueryString = parts.join('&');
return newQueryString.length > 0 ? urlBase + '?' + newQueryString : urlBase;
}
})(jQuery);