'use strict';
$( function () {
$.each( document.querySelectorAll( '.switcher-container' ), function ( i ) {
var activeElement,
switchers = [], showLabels = [], container = this, radioName = 'switcher-' + i,
labelStyle = $( this ).attr( 'data-switcher-label-style' );
if ( labelStyle === undefined ) {
labelStyle = 'display:block';
}
$.each( this.children, function () {
var $radio, switcher = this,
$labelContainer = $( switcher.querySelector('.switcher-label') ),
$labelText = $labelContainer.contents();
if ( !$labelText.length ) {
return;
}
switchers.push( switcher );
$radio = $( '<input type="radio">' ).attr( 'name', radioName ).click( function () {
$( activeElement ).hide();
$( switcher ).show();
activeElement = switcher;
} );
if ( !activeElement ) {
// Mark the first one as selected
activeElement = switcher;
$radio.prop( 'checked', true );
} else if ( $labelContainer.attr( 'data-switcher-default' ) !== undefined ) {
// Custom default
$radio.click();
} else {
// Hide non-default
$( switcher ).hide();
}
showLabels.push( $( '<label></label>' ).attr( 'style', labelStyle ).append( $radio, $labelText ) );
$labelContainer.remove();
} );
if ( switchers.length > 1 ) {
showLabels.push( $( '<label>Show all</label>' ).attr( 'style', labelStyle ).prepend(
$( '<input type="radio">' ).attr( 'name', radioName ).click( function () {
$( switchers ).show();
activeElement = switchers;
} )
) );
if ( $( this ).attr( 'data-switcher-top-choices' ) !== undefined ) {
$( container ).prepend( showLabels );
} else {
$( container ).append( showLabels );
}
}
if ( switchers.length === 1 ) {
$radio.remove();
}
} );
} );