(function () {
	try {
		var cfg  = window.thesplPreviewConfig || {};
		var pid  = cfg.postId || 0;
		var c    = document.getElementById( 'thespl-preview-controls-' + pid );
		var w    = document.getElementById( 'thespl-preview-wrap-' + pid );
		var s    = document.getElementById( 'thespl-preview-shortcode-' + pid );
		var b    = document.getElementById( 'thespl-preview-copy-' + pid );
		var m    = document.getElementById( 'thespl-preview-copied-' + pid );
		var sel  = document.querySelector( 'select[name="thespl_playlist_template"]' );
		var save = document.getElementById( 'thespl-save-btn-' + pid );
		if ( ! w) {
			return;}
		var set = function (px) {
			w.style.maxWidth = String( parseInt( px,10 ) ) + 'px';};
		if (c) {
			c.addEventListener(
				'click',
				function (e) {
					var t = e.target; if ( ! t || t.tagName.toLowerCase() !== 'button') {
						return;}
					var val = t.getAttribute( 'data-w' ); if ( ! val) {
						return;}
					set( val );
					Array.prototype.forEach.call(
						c.querySelectorAll( 'button' ),
						function (bn) {
							bn.classList.remove( 'button-primary' );bn.setAttribute(
								'aria-pressed',
								'false'
							);}
					);
					t.classList.add( 'button-primary' ); t.setAttribute( 'aria-pressed','true' );
				}
			);
		}
		var copy = function () {
			var txt  = s ? s.textContent : '';
			var done = function () {
				if (m) {
						m.style.display = 'inline';setTimeout(
							function () {
								m.style.display = 'none';},
							1500
						);} };
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText( txt ).then( done ).catch( done );} else {
						var ta = document.createElement( 'textarea' ); ta.value = txt; document.body.appendChild( ta ); ta.select();
				try {
					document.execCommand( 'copy' );} catch (e) {
					}
						document.body.removeChild( ta ); done();
				}
		};
		if (b) {
			b.addEventListener(
				'click',
				function () {
						copy();}
			);}
		if (s) {
			s.addEventListener(
				'click',
				function () {
					copy();}
			);
			s.addEventListener(
				'keydown',
				function (e) {
					if (e.key === 'Enter' || e.key === ' ') {
							e.preventDefault();copy();}}
			);
		}
		var updateShortcode = function () {
			var tpl = sel ? sel.value : 'default';
			var sc  = '[thespl_player playlist_id="' + pid + '"]';
			if (tpl && tpl !== 'default') {
				sc = '[thespl_player playlist_id="' + pid + '" template="' + tpl + '"]';}
			if (s) {
				s.textContent = sc;}
		};
		if (sel) {
			sel.addEventListener(
				'change',
				function () {
						updateShortcode();}
			);}
		if (save) {
			save.addEventListener(
				'click',
				function () {
						var pb = document.getElementById( 'publish' );if (pb) {
						pb.click();} else {
								var form = document.getElementById( 'post' ); if (form) {
								form.submit();}}}
			);}
		set( 768 );
	} catch (e) {
	}
})();
