( function () {
	'use strict';
	function initialiseNoticeTray() {
		var host = document.getElementById( 'wpbody-content' );
		var notices, panel, toggle, body, wrap, heading;
		if ( ! host ) { return; }
		if ( host.querySelector( '.speedlyst-notice-tray' ) ) { return; }
		notices = Array.prototype.filter.call(
			host.querySelectorAll( 'div.notice, div.updated' ),
			function ( notice ) {
				return ! notice.closest( '.speedlyst-notice-tray' )
					&& ! notice.classList.contains( 'inline' )
					&& ! notice.classList.contains( 'below-h2' )
					&& ! notice.classList.contains( 'hidden' )
					&& ! notice.classList.contains( 'error' )
					&& ! notice.classList.contains( 'notice-error' )
					&& ! notice.classList.contains( 'notice-warning' );
			}
		);
		if ( 0 === notices.length ) { return; }
		heading = ( window.speedlystNoticeTray && window.speedlystNoticeTray.heading ) || 'Notices';
		panel = document.createElement( 'div' );
		panel.className = 'speedlyst-notice-tray is-collapsed';
		toggle = document.createElement( 'button' );
		toggle.type = 'button';
		toggle.className = 'speedlyst-notice-tray__toggle';
		toggle.setAttribute( 'aria-expanded', 'false' );
		toggle.setAttribute( 'aria-controls', 'speedlyst-notice-tray-body' );
		toggle.textContent = heading + ' (' + notices.length + ')';
		body = document.createElement( 'div' );
		body.id = 'speedlyst-notice-tray-body';
		body.className = 'speedlyst-notice-tray__body';
		body.hidden = true;
		panel.appendChild( toggle );
		panel.appendChild( body );
		wrap = host.querySelector( '.wrap' );
		if ( wrap ) { wrap.insertBefore( panel, wrap.firstChild ); }
		else { host.insertBefore( panel, host.firstChild ); }
		notices.forEach( function ( notice ) { body.appendChild( notice ); } );
		toggle.addEventListener( 'click', function () {
			var isExpanded = 'true' === toggle.getAttribute( 'aria-expanded' );
			panel.classList.toggle( 'is-collapsed', isExpanded );
			toggle.setAttribute( 'aria-expanded', isExpanded ? 'false' : 'true' );
			body.hidden = isExpanded;
		} );
	}
	if ( window.jQuery ) {
		window.jQuery( initialiseNoticeTray );
	} else if ( 'loading' === document.readyState ) {
		document.addEventListener( 'DOMContentLoaded', initialiseNoticeTray );
	} else {
		initialiseNoticeTray();
	}
}() );
