(function (window, document) {
	'use strict';

	/** Carta / Letter vertical (mm). */
	var SHEET_WIDTH_MM = 215.9;
	var SHEET_HEIGHT_MM = 279.4;

	function escapeHtml(value) {
		return String(value == null ? '' : value)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;');
	}

	function displayValue(value) {
		var text = String(value == null ? '' : value).trim();
		return text === '' ? '&nbsp;' : escapeHtml(text);
	}

	function formatNumber(value) {
		var num = Number(value);
		if (!isFinite(num) || num <= 0) {
			return '';
		}
		return String(Math.round(num)).replace(/\B(?=(\d{3})+(?!\d))/g, '.');
	}

	function formatReferencia(value) {
		return String(value == null ? '' : value).trim().toUpperCase();
	}

	function readJobFromForm(form) {
		if (!form) {
			return null;
		}

		var referenciaInput = form.querySelector('[data-estiba-referencia]');
		var cajasInput = form.querySelector('[data-estiba-cajas]');
		var undInput = form.querySelector('[data-estiba-und-caja]');
		var copiasInput = form.querySelector('[data-estiba-copias]');
		var accentInput = form.querySelector('[data-estiba-accent]');
		var swatch = form.querySelector('[data-estiba-accent-swatch]');
		var referencia = formatReferencia(referenciaInput && referenciaInput.value ? referenciaInput.value : '');
		var cajas = parseInt(String(cajasInput && cajasInput.value ? cajasInput.value : ''), 10);
		var undCaja = parseInt(String(undInput && undInput.value ? undInput.value : ''), 10);
		var copias = parseInt(String(copiasInput && copiasInput.value ? copiasInput.value : '1'), 10);
		var accent = normalizeAccent(accentInput && accentInput.value ? accentInput.value : DEFAULT_ACCENT);
		var totalField = form.querySelector('[data-estiba-total]');
		var total = cajas * undCaja;

		if (totalField) {
			totalField.value = isFinite(total) && total > 0 ? formatNumber(total) : '';
		}
		if (swatch) {
			swatch.style.background = accent;
		}

		return {
			referencia: referencia,
			cantidad_cajas: isFinite(cajas) ? cajas : 0,
			unidades_por_caja: isFinite(undCaja) ? undCaja : 0,
			total: isFinite(total) && total > 0 ? total : 0,
			num_copias: isFinite(copias) && copias > 0 ? Math.min(50, copias) : 1,
			accent_color: accent
		};
	}

	function validateJob(job) {
		if (!job || !job.referencia) {
			return 'Indica la referencia.';
		}
		if (!job.cantidad_cajas || job.cantidad_cajas < 1) {
			return 'La cantidad de cajas debe ser mayor que 0.';
		}
		if (!job.unidades_por_caja || job.unidades_por_caja < 1) {
			return 'Las unidades por caja deben ser mayor que 0.';
		}
		if (!job.total || job.total < 1) {
			return 'El total no es válido.';
		}
		return '';
	}

	var DEFAULT_ACCENT = '#86efac';

	function normalizeAccent(value) {
		var color = String(value || '').trim();
		if (/^#[0-9A-Fa-f]{6}$/.test(color)) {
			return color;
		}
		return DEFAULT_ACCENT;
	}

	function buildEstibaLabelHtml(job, options) {
		options = options || {};
		var accent = normalizeAccent(job && job.accent_color);
		var labelClass = 'logistica-estiba-label'
			+ (options.preview ? ' is-preview' : '')
			+ (options.printSlot ? ' is-print-slot' : '');
		var varsStyle = '--estiba-label-w-mm:' + SHEET_WIDTH_MM + ';--estiba-label-h-mm:' + SHEET_HEIGHT_MM + ';';
		var sizeStyle = options.preview
			? (' style="' + varsStyle + 'width:100%;height:100%;"')
			: (' style="' + varsStyle + 'width:' + SHEET_WIDTH_MM + 'mm;height:' + SHEET_HEIGHT_MM + 'mm;"');
		var headStyle = ' style="background-color:' + escapeHtml(accent) + ';"';

		return (
			'<article class="' + labelClass + '"' + sizeStyle + '>' +
				'<section class="logistica-estiba-label__block logistica-estiba-label__block--ref">' +
					'<header class="logistica-estiba-label__head"' + headStyle + '>REFERENCIA</header>' +
					'<div class="logistica-estiba-label__value logistica-estiba-label__value--ref" data-estiba-fit="wrap">' +
						'<span class="logistica-estiba-label__fit-text">' + displayValue(job.referencia) + '</span>' +
					'</div>' +
				'</section>' +
				'<div class="logistica-estiba-label__split">' +
					'<section class="logistica-estiba-label__block logistica-estiba-label__block--half">' +
						'<header class="logistica-estiba-label__head"' + headStyle + '>CAJAS</header>' +
						'<div class="logistica-estiba-label__value" data-estiba-fit="nowrap">' +
							'<span class="logistica-estiba-label__fit-text">' + displayValue(formatNumber(job.cantidad_cajas)) + '</span>' +
						'</div>' +
					'</section>' +
					'<section class="logistica-estiba-label__block logistica-estiba-label__block--half">' +
						'<header class="logistica-estiba-label__head"' + headStyle + '>UND/CAJA</header>' +
						'<div class="logistica-estiba-label__value" data-estiba-fit="nowrap">' +
							'<span class="logistica-estiba-label__fit-text">' + displayValue(formatNumber(job.unidades_por_caja)) + '</span>' +
						'</div>' +
					'</section>' +
				'</div>' +
				'<section class="logistica-estiba-label__block logistica-estiba-label__block--total">' +
					'<header class="logistica-estiba-label__head"' + headStyle + '>TOTAL</header>' +
					'<div class="logistica-estiba-label__value" data-estiba-fit="nowrap">' +
						'<span class="logistica-estiba-label__fit-text">' + displayValue(formatNumber(job.total)) + '</span>' +
					'</div>' +
				'</section>' +
			'</article>'
		);
	}

	function getBoxContentSize(box) {
		var style = window.getComputedStyle(box);
		var padX = (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0);
		var padY = (parseFloat(style.paddingTop) || 0) + (parseFloat(style.paddingBottom) || 0);
		var width = Math.max(0, box.clientWidth - padX);
		var height = Math.max(0, box.clientHeight - padY);

		return {
			width: width,
			height: height
		};
	}

	function textFitsAvailable(textEl, availW, availH, nowrap) {
		if (availW <= 0 || availH <= 0) {
			return true;
		}
		if (nowrap) {
			return textEl.offsetWidth <= availW && textEl.offsetHeight <= availH;
		}
		return textEl.scrollHeight <= availH && textEl.offsetWidth <= availW + 1;
	}

	function fitOneBox(box) {
		var text = box.querySelector('.logistica-estiba-label__fit-text');
		var nowrap;
		var content;
		var availW;
		var availH;
		var minPx;
		var maxPx;
		var lo;
		var hi;
		var mid;
		var best;

		if (!text) {
			return;
		}

		nowrap = box.getAttribute('data-estiba-fit') === 'nowrap';
		content = getBoxContentSize(box);
		/* Margen de seguridad para evitar cortes por métricas de fuente (descendentes / anchos). */
		availW = Math.floor(content.width * (nowrap ? 0.86 : 0.90));
		availH = Math.floor(content.height * (nowrap ? 0.78 : 0.82));

		if (availW < 8 || availH < 8) {
			return;
		}

		minPx = 10;
		maxPx = Math.max(minPx, Math.floor(Math.min(availW, availH) * (nowrap ? 0.95 : 0.85)));

		text.style.display = 'inline-block';
		text.style.boxSizing = 'border-box';
		text.style.fontWeight = '800';
		text.style.lineHeight = nowrap ? '1' : '1.12';
		text.style.textAlign = 'center';
		text.style.overflow = 'visible';
		text.style.maxWidth = 'none';
		text.style.maxHeight = 'none';
		text.style.margin = '0';
		text.style.padding = '0';

		if (nowrap) {
			text.style.whiteSpace = 'nowrap';
			text.style.wordBreak = 'normal';
			text.style.overflowWrap = 'normal';
			text.style.width = 'auto';
		} else {
			text.style.whiteSpace = 'normal';
			text.style.wordBreak = 'break-word';
			text.style.overflowWrap = 'anywhere';
			text.style.width = availW + 'px';
		}

		lo = minPx;
		hi = maxPx;
		best = minPx;

		while (lo <= hi) {
			mid = Math.floor((lo + hi) / 2);
			text.style.fontSize = mid + 'px';
			if (textFitsAvailable(text, availW, availH, nowrap)) {
				best = mid;
				lo = mid + 1;
			} else {
				hi = mid - 1;
			}
		}

		/* Un punto extra de holgura para bordes y descendentes. */
		best = Math.max(minPx, best - 1);
		text.style.fontSize = best + 'px';

		if (!textFitsAvailable(text, availW, availH, nowrap) && best > minPx) {
			best -= 1;
			text.style.fontSize = best + 'px';
		}

		if (!nowrap) {
			text.style.maxWidth = availW + 'px';
		}
	}

	function fitTextBoxes(root) {
		if (!root || !root.querySelectorAll) {
			return;
		}

		root.querySelectorAll('[data-estiba-fit]').forEach(fitOneBox);
	}

	function getFitScript() {
		return (
			'(function(){' +
			'function size(box){var s=getComputedStyle(box);var x=(parseFloat(s.paddingLeft)||0)+(parseFloat(s.paddingRight)||0);var y=(parseFloat(s.paddingTop)||0)+(parseFloat(s.paddingBottom)||0);return{w:Math.max(0,box.clientWidth-x),h:Math.max(0,box.clientHeight-y)};}' +
			'function ok(t,aw,ah,nowrap){if(aw<=0||ah<=0)return true;if(nowrap)return t.offsetWidth<=aw&&t.offsetHeight<=ah;return t.scrollHeight<=ah&&t.offsetWidth<=aw+1;}' +
			'function fitOne(box){var t=box.querySelector(".logistica-estiba-label__fit-text");if(!t)return;' +
			'var nowrap=box.getAttribute("data-estiba-fit")==="nowrap";var c=size(box);' +
			'var aw=Math.floor(c.w*(nowrap?0.86:0.90));var ah=Math.floor(c.h*(nowrap?0.78:0.82));' +
			'if(aw<8||ah<8)return;' +
			'var min=10,max=Math.max(min,Math.floor(Math.min(aw,ah)*(nowrap?0.95:0.85)));' +
			't.style.display="inline-block";t.style.boxSizing="border-box";t.style.fontWeight="800";' +
			't.style.lineHeight=nowrap?"1":"1.12";t.style.textAlign="center";t.style.overflow="visible";' +
			't.style.maxWidth="none";t.style.maxHeight="none";t.style.margin="0";t.style.padding="0";' +
			'if(nowrap){t.style.whiteSpace="nowrap";t.style.wordBreak="normal";t.style.overflowWrap="normal";t.style.width="auto";}' +
			'else{t.style.whiteSpace="normal";t.style.wordBreak="break-word";t.style.overflowWrap="anywhere";t.style.width=aw+"px";}' +
			'var lo=min,hi=max,best=min,mid;' +
			'while(lo<=hi){mid=(lo+hi)>>1;t.style.fontSize=mid+"px";if(ok(t,aw,ah,nowrap)){best=mid;lo=mid+1;}else{hi=mid-1;}}' +
			'best=Math.max(min,best-1);t.style.fontSize=best+"px";' +
			'if(!ok(t,aw,ah,nowrap)&&best>min){best-=1;t.style.fontSize=best+"px";}' +
			'if(!nowrap){t.style.maxWidth=aw+"px";}}' +
			'function fit(){document.querySelectorAll("[data-estiba-fit]").forEach(fitOne);}' +
			'if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",fit);}else{fit();}' +
			'setTimeout(fit,40);setTimeout(fit,160);setTimeout(fit,320);' +
			'})();'
		);
	}

	function getEmbeddedPrintCss() {
		return ''
			+ '@page{size:' + SHEET_WIDTH_MM + 'mm ' + SHEET_HEIGHT_MM + 'mm;margin:0;}'
			+ 'html,body{margin:0!important;padding:0!important;background:#fff!important;}'
			+ 'body.logistica-estiba-label-print-doc{background:#fff!important;}'
			+ '.logistica-estiba-label-print-page{'
			+ 'box-sizing:border-box;'
			+ 'height:' + SHEET_HEIGHT_MM + 'mm;'
			+ 'margin:0;'
			+ 'padding:0;'
			+ 'page-break-after:always;'
			+ 'break-after:page;'
			+ 'width:' + SHEET_WIDTH_MM + 'mm;'
			+ '}'
			+ '.logistica-estiba-label-print-page:last-child{page-break-after:auto;break-after:auto;}'
			+ '.logistica-estiba-label{'
			+ 'background:#fff!important;'
			+ 'border:1.2mm solid #111;'
			+ 'box-sizing:border-box;'
			+ 'color:#111;'
			+ 'display:flex;'
			+ 'flex-direction:column;'
			+ 'font-family:Arial,Helvetica,sans-serif;'
			+ 'height:' + SHEET_HEIGHT_MM + 'mm;'
			+ 'margin:0;'
			+ 'overflow:hidden;'
			+ 'width:' + SHEET_WIDTH_MM + 'mm;'
			+ '-webkit-print-color-adjust:exact;'
			+ 'print-color-adjust:exact;'
			+ '}'
			/* Proporciones fijas del rótulo Carta: ref 44%, cajas 26%, total 30%. */
			+ '.logistica-estiba-label__block{border-bottom:0.9mm solid #111;box-sizing:border-box;display:flex;flex-direction:column;min-height:0;overflow:hidden;}'
			+ '.logistica-estiba-label__block:last-child{border-bottom:0;}'
			+ '.logistica-estiba-label__block--ref{flex:0 0 44%;height:44%;}'
			+ '.logistica-estiba-label__split{display:flex;flex:0 0 26%;height:26%;min-height:0;}'
			+ '.logistica-estiba-label__block--half{border-right:0.9mm solid #111;flex:1 1 50%;height:100%;min-width:0;overflow:hidden;}'
			+ '.logistica-estiba-label__block--half:last-child{border-right:0;}'
			+ '.logistica-estiba-label__block--total{flex:0 0 30%;height:30%;}'
			+ '.logistica-estiba-label__head{'
			+ 'align-items:center;'
			+ 'box-sizing:border-box;'
			+ 'color:#111;'
			+ 'display:flex;'
			+ 'flex:0 0 22%;'
			+ 'font-size:5.2mm;'
			+ 'font-weight:800;'
			+ 'height:22%;'
			+ 'justify-content:center;'
			+ 'letter-spacing:0.04em;'
			+ 'line-height:1;'
			+ 'padding:0 3mm;'
			+ 'text-align:center;'
			+ 'text-transform:uppercase;'
			+ '-webkit-print-color-adjust:exact;'
			+ 'print-color-adjust:exact;'
			+ '}'
			+ '.logistica-estiba-label__value{'
			+ 'align-items:center;'
			+ 'background:#fff;'
			+ 'box-sizing:border-box;'
			+ 'display:flex;'
			+ 'flex:0 0 78%;'
			+ 'height:78%;'
			+ 'justify-content:center;'
			+ 'min-height:0;'
			+ 'overflow:hidden;'
			+ 'padding:3.5mm 5mm;'
			+ 'text-align:center;'
			+ 'width:100%;'
			+ '}'
			+ '.logistica-estiba-label__fit-text{'
			+ 'display:inline-block;'
			+ 'font-weight:800;'
			+ 'text-align:center;'
			+ '}'
			+ '.logistica-estiba-label__value[data-estiba-fit="nowrap"] .logistica-estiba-label__fit-text{white-space:nowrap;}'
			+ '@media print{'
			+ 'html,body{width:' + SHEET_WIDTH_MM + 'mm;height:auto;}'
			+ '*{-webkit-print-color-adjust:exact!important;print-color-adjust:exact!important;}'
			+ '}';
	}

	function buildPrintDocument(job, copies) {
		var pages = [];
		var i;
		var count = Math.max(1, copies || 1);

		for (i = 0; i < count; i++) {
			pages.push(
				'<div class="logistica-estiba-label-print-page">' +
					buildEstibaLabelHtml(job, { preview: false }) +
				'</div>'
			);
		}

		return (
			'<!DOCTYPE html><html lang="es"><head><meta charset="utf-8">' +
			'<title>\u200b</title>' +
			'<style>' + getEmbeddedPrintCss() + '</style>' +
			'</head><body class="logistica-estiba-label-print-doc">' +
			pages.join('') +
			'<script>' + getFitScript() + '<\/script>' +
			'</body></html>'
		);
	}

	function removePrintFrame() {
		var frame = document.getElementById('logistica-estiba-label-print-frame');
		if (frame && frame.parentNode) {
			frame.parentNode.removeChild(frame);
		}
	}

	function printJob(job, copies) {
		var html = buildPrintDocument(job, copies);

		removePrintFrame();

		var iframe = document.createElement('iframe');
		iframe.id = 'logistica-estiba-label-print-frame';
		iframe.setAttribute('aria-hidden', 'true');
		iframe.setAttribute('tabindex', '-1');
		iframe.style.cssText = 'border:0;clip:rect(0,0,0,0);height:0;overflow:hidden;position:fixed;right:0;bottom:0;width:0;';
		document.body.appendChild(iframe);

		return new Promise(function (resolve, reject) {
			var finished = false;

			function finish(error) {
				if (finished) {
					return;
				}
				finished = true;
				iframe.onload = null;
				setTimeout(removePrintFrame, 1500);
				if (error) {
					reject(error);
					return;
				}
				resolve({ count: copies });
			}

			iframe.onload = function () {
				var printWindow = iframe.contentWindow;
				var printDoc;
				if (!printWindow) {
					finish(new Error('No se pudo preparar la impresión.'));
					return;
				}

				try {
					printDoc = printWindow.document;
					if (printDoc) {
						fitTextBoxes(printDoc);
					}
				} catch (fitError) {
					// Ignore cross-frame measurement errors.
				}

				setTimeout(function () {
					try {
						if (printWindow.document) {
							fitTextBoxes(printWindow.document);
						}
						printWindow.focus();
						printWindow.print();
						finish(null);
					} catch (printError) {
						finish(printError);
					}
				}, 700);
			};

			iframe.onerror = function () {
				finish(new Error('No se pudo cargar el documento de impresión.'));
			};

			iframe.srcdoc = html;
		});
	}

	function setStatus(board, message, isError) {
		var status = board ? board.querySelector('[data-rotulo-estibas-status]') : null;
		if (!status) {
			return;
		}
		status.textContent = message || '';
		status.classList.toggle('is-error', !!isError);
	}

	function renderPreview(board, job) {
		var mount = board ? board.querySelector('[data-rotulo-estibas-preview]') : null;
		if (!mount) {
			return;
		}
		mount.innerHTML =
			'<div class="logistica-estiba-label-preview-scaler" style="--estiba-preview-w:' + SHEET_WIDTH_MM + ';--estiba-preview-h:' + SHEET_HEIGHT_MM + ';">' +
				buildEstibaLabelHtml(job || {}, { preview: true }) +
			'</div>';

		window.requestAnimationFrame(function () {
			fitTextBoxes(mount);
			window.setTimeout(function () {
				fitTextBoxes(mount);
			}, 60);
		});
	}

	function syncTotal(form) {
		readJobFromForm(form);
	}

	function activateModuleTab(module, tabId) {
		if (!module || !tabId) {
			return;
		}

		module.querySelectorAll('[data-rotulos-module-tab]').forEach(function (btn) {
			var active = btn.getAttribute('data-rotulos-module-tab') === tabId;
			btn.classList.toggle('is-active', active);
			btn.setAttribute('aria-selected', active ? 'true' : 'false');
		});

		module.querySelectorAll('[data-rotulos-module-tab-panel]').forEach(function (panel) {
			var active = panel.getAttribute('data-rotulos-module-tab-panel') === tabId;
			panel.classList.toggle('is-active', active);
			if (active) {
				panel.removeAttribute('hidden');
			} else {
				panel.setAttribute('hidden', 'hidden');
			}
		});
	}

	function bindModuleTabs(module) {
		if (!module || module.dataset.rotulosTabsBound === '1') {
			return;
		}

		module.dataset.rotulosTabsBound = '1';

		module.addEventListener('click', function (event) {
			var btn = event.target.closest('[data-rotulos-module-tab]');
			if (!btn || !module.contains(btn)) {
				return;
			}
			activateModuleTab(module, btn.getAttribute('data-rotulos-module-tab'));
		});

		module.addEventListener('keydown', function (event) {
			var tabs = Array.prototype.slice.call(module.querySelectorAll('[data-rotulos-module-tab]'));
			var current = event.target.closest('[data-rotulos-module-tab]');
			var index;
			var next;

			if (!current || tabs.indexOf(current) === -1) {
				return;
			}

			index = tabs.indexOf(current);
			if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
				event.preventDefault();
				next = tabs[(index + 1) % tabs.length];
			} else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
				event.preventDefault();
				next = tabs[(index - 1 + tabs.length) % tabs.length];
			} else if (event.key === 'Home') {
				event.preventDefault();
				next = tabs[0];
			} else if (event.key === 'End') {
				event.preventDefault();
				next = tabs[tabs.length - 1];
			}

			if (next) {
				next.focus();
				activateModuleTab(module, next.getAttribute('data-rotulos-module-tab'));
			}
		});
	}

	function scrollEstibaPreviewIntoView(board) {
		var preview = board ? board.querySelector('.logistica-rotulo-estibas-preview-column') || board.querySelector('[data-rotulo-estibas-preview]') : null;
		if (!preview || typeof preview.scrollIntoView !== 'function') {
			return;
		}

		preview.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
	}

	function bindEstibasBoard(board) {
		var form;

		if (!board || board.dataset.estibasBound === '1') {
			return;
		}

		board.dataset.estibasBound = '1';
		form = board.querySelector('[data-rotulo-estibas-form]');
		if (!form) {
			return;
		}

		form.addEventListener('input', function () {
			var job = readJobFromForm(form);
			renderPreview(board, job);
		});

		form.addEventListener('change', function () {
			var job = readJobFromForm(form);
			renderPreview(board, job);
		});

		form.addEventListener('submit', function (event) {
			var job = readJobFromForm(form);
			var error = validateJob(job);

			event.preventDefault();

			if (error) {
				setStatus(board, error, true);
				return;
			}

			setStatus(board, 'Abriendo impresión en Carta…', false);
			printJob(job, job.num_copias)
				.then(function () {
					setStatus(
						board,
						'Impresión lista. Usa márgenes «Ninguno», sin encabezados/pies y «Gráficos de fondo».',
						false
					);
				})
				.catch(function (err) {
					setStatus(board, (err && err.message) || 'No se pudo imprimir.', true);
				});
		});

		board.addEventListener('click', function (event) {
			var previewBtn = event.target.closest('[data-estiba-preview]');
			var job;
			var error;

			if (!previewBtn || !board.contains(previewBtn)) {
				return;
			}

			job = readJobFromForm(form);
			error = validateJob(job);
			renderPreview(board, job);
			scrollEstibaPreviewIntoView(board);
			if (error) {
				setStatus(board, error, true);
				return;
			}

			setStatus(board, 'Vista previa actualizada.', false);
		});

		syncTotal(form);
		renderPreview(board, readJobFromForm(form));
	}

	function init(root) {
		var scope = root && root.querySelectorAll ? root : document;

		scope.querySelectorAll('[data-rotulos-module]').forEach(bindModuleTabs);
		scope.querySelectorAll('[data-rotulo-estibas-board]').forEach(bindEstibasBoard);

		if (root && root.matches) {
			if (root.matches('[data-rotulos-module]')) {
				bindModuleTabs(root);
			}
			if (root.matches('[data-rotulo-estibas-board]')) {
				bindEstibasBoard(root);
			}
		}
	}

	window.LogisticaRotuloEstibasPrint = {
		init: init,
		readJobFromForm: readJobFromForm,
		validateJob: validateJob,
		buildEstibaLabelHtml: buildEstibaLabelHtml,
		printJob: printJob,
		renderPreview: renderPreview
	};

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', function () {
			init(document);
		});
	} else {
		init(document);
	}

	document.addEventListener('logistica:tab-loaded', function (event) {
		var detail = event && event.detail ? event.detail : {};
		if (detail.panel) {
			init(detail.panel);
		}
	});
}(window, document));
