(function () {
	CKEDITOR.dialog.add("accordion", function (editor) {
		return {
			title: "Include Page",
			minWidth: 400,
			minHeight: 200,
			contents: [
				{
					id: "Include Page",
					label: "포함할 문서 선택",
					elements: [
						{
							type: "hbox",
							widths: ["30%", "70%"],
							children: [
								{
									type: "select",
									id: "Doc Selector",
									label: "포함할 문서 선택",
									items: [["로딩 중..."]],
									onChange: function () {
										var wikiId = "WIKI_" + $("#selected_pdService").val() + "_" + this.getValue();

										var dialog = this.getDialog();
										var $preview = $(dialog.getContentElement("Include Page", "Doc Preview").getElement().$).find(
											".ckeditor_preview"
										);

										$.ajax({
											type: "GET",
											url: "/auth-user/api/arms/wiki/" + wikiId + "/getWiki.do",
											contentType: "application/json;charset=UTF-8",
											dataType: "json",
											success: function (data) {
												$preview.empty().append(data.contents);
											}
										});
									}
								},
								{
									type: "html",
									id: "Doc Preview",
									html:
										"<div>미리보기" +
										"<div class='ckeditor_preview' style='height: 250px; border: 2px solid #d1d1d1; padding: 10px 20px'></div>" +
										"</div>"
								}
							]
						}
					]
				}
			],
			onShow: function () {
				var dialog = this;
				var $select = $(dialog.getContentElement("Include Page", "Doc Selector").getInputElement().$);

				$.ajax({
					url: "/auth-user/api/arms/wiki/T_ARMS_WIKI_" + $("#selected_pdService").val() + "/getNodesWithoutRoot.do",
					dataType: "json",
					type: "GET",
					success: function (data) {
						$select.empty();

						data.result.forEach(function (item) {
							if (item.c_type !== "default") return;

							$select.append($("<option />").val(item.c_id).text(item.c_title));
						});
					}
				});
			},
			onOk: function () {
				var dialog = this;
				var select = dialog.getContentElement("Include Page", "Doc Selector").getInputElement().$;
				var selectedOption = select.options[select.selectedIndex];

				var widgetDef = editor.widgets.registered.accordion;
				var temp = new CKEDITOR.template(widgetDef.template.source);
				var element = CKEDITOR.dom.element.createFromHtml(temp.output());

				editor.insertElement(element);
				editor.widgets.initOn(element, "accordion", {
					title: selectedOption.text,
					id: selectedOption.value
				});
			},
			onHide: function () {
				var dialog = this;
				var $select = $(dialog.getContentElement("Include Page", "Doc Selector").getInputElement().$);
				var $preview = $(dialog.getContentElement("Include Page", "Doc Preview").getElement().$).find(
					".ckeditor_preview"
				);

				$select.empty();
				$preview.empty();
			}
		};
	});
})();
