document.addEventListener("DOMContentLoaded", function() {
	var accordions = [].slice.call(document.querySelectorAll(".wp-block-greyd-accordion"));
	
	accordions.forEach(function(accordion) {

		const autoClose = accordion.dataset.autoclose == 'true';
		const openFirst = accordion.dataset.openfirst == 'true';

		const titles = [].slice.call(accordion.querySelectorAll('.wp-block-greyd-accordion__title'));

		if ( ! titles.length ) return;

		if ( openFirst ) {
			titles[0].setAttribute('aria-expanded', 'true');
		}

		titles.forEach(function(title) {
			title.addEventListener( 'click', function(e) {
	
				if ( title.getAttribute('aria-expanded') == 'false' ) {
	
					if ( autoClose ) {
						const activeSections = accordion.querySelectorAll('.wp-block-greyd-accordion__title[aria-expanded="true"]');
						Array.prototype.forEach.call(activeSections, function (section) {
							section.setAttribute('aria-expanded', 'false');
						});
					}
					title.setAttribute('aria-expanded', 'true');
				}
				else {
					title.setAttribute('aria-expanded', 'false');
				}
			} )
		});

	});
});