CKEDITOR.dialog.add( 'personeDialog', function( editor ) {

	// $.getJSON( "/person/Ajaxlist", function( data, ok )  {
	//
	// 	for (var key in data) {
	// 		persone = '<option value="'+data[key]['alias']+'">'+data[key]['name']+'</option>';
	// 		$('select.cke_dialog_ui_input_select').append(persone);
	// 	}
	//
	// });
	let selection = '';
    return {
        title: 'Добавить персону',
        minWidth: 400,
        minHeight: 200,

        contents: [
        {
            id: 'tab',
            label: 'first tab',
            elements: [
            {
                type : 'select',
                id: null,
                label: 'Выберите из списка',
				items :  [],
				'default' : '',
            }]
        }],

		onOk : function()
		    {
				if(selection!==''){
					const selectionText = editor.getSelection();
					const person = editor.document.createElement( 'a' );
					if(selectionText.getSelectedText()===''){
							person.setAttribute( 'href', selection.alias );
							person.setAttribute( 'class', 'person-inject' );
							person.setHtml( selection.name );
							editor.insertElement( person );

					} else {
						person.setAttribute( 'href', selection.alias );
						person.setAttribute( 'class', 'person' );
						person.setHtml( selectionText.getSelectedText() );
						editor.insertElement( person );
					}
				}
			},
		onShow: function () {
			$('.cke_dialog_ui_input_select').css({width:"100%"});
			$('select.cke_dialog_ui_input_select').select2({
				language: "ru",
				ajax: {
					url: "/person/Ajaxlist",
					dataType: 'json',
					delay: 250,
					data: function (params) {
						return {
							q: params.term,
							page: params.page
						};
					},
					processResults: function (data, params) {
						params.page = params.page || 1;
						return {
							results: data.items,
						};
					},
					cache: true
				},
				placeholder: 'Поиск персоны',
				minimumInputLength: 1,
				templateResult: formatRepo,
				templateSelection: formatRepoSelection
			});

			function formatRepo (repo) {
				if (repo.loading) {
					return repo.text;
				}

				var $container = $(
					"<div class='select2-result-repository clearfix'>" +
					"<div class='select2-result-repository__avatar' style='width: 70px; height: 70px; overflow: hidden; float: left; margin-right: 20px;'><img style='width: 100%; height: auto;' src='" + repo.avatar_url + "' /></div>" +
					"<div class='select2-result-repository__meta'>" +
						"<div class='select2-result-repository__title' style='font-weight: bold;'></div>" +
						"<div class='select2-result-repository__description'></div>" +
					"</div>" +
					"</div>"
				);
				$container.find(".select2-result-repository__title").text(repo.name);
				$container.find(".select2-result-repository__description").text(repo.description);
				return $container;
			}

			function formatRepoSelection (repo) {
				selection = repo;
				return repo.name || repo.text;
			}
		}
    };
});
