var tables = $('.custom-table');
tables.each(function(el) {
	var element = $(this);
	var table = element.DataTable(
		{
			paging:   false,
			ordering: true,
			columnDefs: [
				{orderable: false, targets:  "no-sort"}
			],
			searching: false,
		}
	)
	var rows_selected = [];
	$(element).find('tbody').on('click', 'input[type="checkbox"]', function(e) {
		var $row = $(this).closest('tr');

		// Get row data
		var data = table.row($row).data();

		// Get row ID
		var rowId = data[0];

		// Determine whether row ID is in the list of selected row IDs
		var index = $.inArray(rowId, rows_selected);

		// If checkbox is checked and row ID is not in list of selected row IDs
		if(this.checked && index === -1){
			rows_selected.push(rowId);

		// Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
		} else if (!this.checked && index !== -1){
			rows_selected.splice(index, 1);
		}

		if(this.checked){
			$row.addClass('selected');
		} else {
			$row.removeClass('selected');
		}

		// Update state of "Select all" control
		updateDataTableSelectAllCtrl(table);

		// Prevent click event from propagating to parent
		e.stopPropagation();
	});

	// Handle click on "Select all" control
	$(element).find('thead input[id="check_all"]').on('click', function(e){
		if(this.checked){
			$(element).find('tbody input[type="checkbox"]:not(:checked)').trigger('click');
		} else {
			$(element).find('tbody input[type="checkbox"]:checked').trigger('click');
		}
		// Prevent click event from propagating to parent
		e.stopPropagation();
	});
	
})


$(document).ready(function() {
    // Aggiunge un listener di evento 'click' a tutti gli elementi con la classe '.btn-table-collapse'
    $('.btn-table-collapse').on('click', function() {

		// Elemento da mostrare/nascondere
		const collapsedElement = $(this).attr('href');

        // Trova il `<td>` che contiene `.btn-table-collapse`, passa al `<td>` successivo e ottieni il contenuto di `.table-ctas`
        const rowCtas = $(this).closest('td').next('td').find('.table-ctas');
		const rowCtasContent = $(rowCtas).html();

        // Trova il div `.expanded-row-ctas` successivo e sostituisci il suo contenuto con `tableCtasContent`
        $(this).closest('tr').next('tr').find('.expanded-row-ctas').html(rowCtasContent);

		// Toggle l'attributo aria-expanded
        const isExpanded = $(this).attr('aria-expanded') === 'true';
        $(this).attr('aria-expanded', !isExpanded);
		$(collapsedElement).attr('aria-expanded', !isExpanded);

		// Toggle della visibilità
		const isVisible = rowCtas.css('visibility') === 'visible';
        rowCtas.css('visibility', isVisible ? 'hidden' : 'visible');
		$(collapsedElement).toggle();
    });
});