/*
TOC Switcher Gadget - JS Initialisation, Setup, Events
See detailed documentation in Dev/mediawiki
deferrable:YES -- This is just an augmentation
*/

(function() {

	if( $('#toc').length ) {
		
		let cookieName = 'ctbc_tocLevelSet';

		// If there's no level 2, TocLevelSwitcher can do nothing
		if( $('.toclevel-2').length == 0 ) return;

		// Setup

		let panel = $(''
			+ '<div id="toc-level-switcher">'
			+  '<span data-level="all" title="Show all levels"><i class="fas fa-star"></i></span>'
			// If there's no level 3, then button "Show 2 levels" can do nothing
			+  ( $('.toclevel-3').length == 0 ? '' : '<span data-level="two" title="Show 2 levels">2</span>' )
			+  '<span data-level="one" title="Show 1 level">1</span>'
			+ '</div>'
		);

		if( $('#toc .toctogglecheckbox').length ) {
			panel.insertAfter( $('#toc .toctogglecheckbox') );
		} else {
			$('#toc').prepend( panel );
		}

		$('#toc').addClass( 'toc-level-switcher-enhanced' );

		let opener = $( '<span class="toc-level-switcher-opener"><i class="fas fa-plus"></i></span>' );

		let counter = $( '<span class="toc-level-switcher-counter">(<span class="count"></span>)</span>' );

		// Events

		$('#toc-level-switcher > span').on( 'click', function() {
			$(this).siblings().removeClass('active');
			$(this).addClass('active');

			let highestLevel = $(this).attr('data-level');
			
			$('body').removeClass( cookieName + '_' + Cookies.get( cookieName ) );
			if( highestLevel == 'all' ) {
				Cookies.remove( cookieName );
			} else {
				Cookies.set( cookieName, highestLevel, { sameSite: 'strict' } );
				$( 'body' ).addClass( cookieName + '_' + highestLevel );
			}

			if( highestLevel == 'all' ) {
				$('#toc').removeAttr('data-level');
			} else {
				$('#toc').attr('data-level', highestLevel );
			}

			$('.toc-level-switcher-opener').remove();
			$('.toc-level-switcher-counter').remove();

			$('.toclevel-1, .toclevel-2').removeClass('toc-level-switcher-show');

			let enrichLevel = function() {
				let $this = $(this);

				let nextLevel = $this.hasClass('toclevel-1') ? '.toclevel-2' : '.toclevel-3';
				let count = $this.find( nextLevel ).length;

				if( count == 0 ) return;

				let c = counter.clone();
				c.find('.count').text( count );
				$this.find('.toctext').eq(0).append( c );

				let o = opener.clone();
				$this.prepend( o );

				// Events

				o.on( 'click', function() {
					$this.addClass('toc-level-switcher-show');
					o.remove();
				});
			};

			switch( highestLevel ) {
				case 'one':
					$('.toclevel-1').each( enrichLevel );
					$('.toclevel-2').each( enrichLevel );
				break;
				case 'two':
					$('.toclevel-2').each( enrichLevel );
				break;
			}

		});
		
		// Execute at startup

		let cookieValue = Cookies.get( cookieName );
		if( cookieValue ) $( `#toc-level-switcher > span[data-level=${ cookieValue }]` )[0].click();

	}

})();

/*
[[Category:MultiWiki]]
*/