var galleryDropdownInitialized = false;
var galleryObject;
CKEDITOR.dialog.add( 'ck-gallery', function( editor ) {
	return {
		title: 'Edit Gallery',
		minWidth: 200,
		minHeight: 100,
		contents: [
			{
				id: 'info',
				elements: [
					{
						id: 'ck-gallery',
						type: 'select',
						label: 'Select gallery',
						items: [  ],
						'default': '',
						validate: CKEDITOR.dialog.validate.notEmpty( "This field cannot be empty." ),

						setup: function( widget ) {
							var element_id = '#' + this.getInputElement().$.id;
							var selectElement = document.querySelector(element_id);
							if(galleryDropdownInitialized == false){
								$.ajax({
									type: 'GET',
									url: ajaxPrefix+'/ajax/get-galleries',
									contentType: 'application/json; charset=utf-8',
									dataType: 'json',
									async: false,
									success: function(data) {
										data = JSON.parse(data);
                                        galleryObject = data;
										for (let i = 0; i < data.length; i++) {
											var option = document.createElement("option");
											option.text = data[i].title;
											option.value = data[i].id;
											option.setAttribute('data-author', data[i].author);
											option.setAttribute('data-image', data[i].image);

											//option.value = data[i].id;
											selectElement.add(option);

										}

										galleryDropdownInitialized = true;
									},
									error:function (xhr, ajaxOptions, thrownError){
										console.log(xhr.status);
										console.log(thrownError);
									}
								});

								//this.setValue( widget.data.galleryObj = galleryObject);
							}
						},

						commit: function( widget ) {
							var galleryID = this.getValue();
                            widget.setData( 'galleryID', galleryID);
							galleryObject.forEach(function(el){
								if(el.id == galleryID){
                                    widget.setData( 'galleryName', el.title);
                                    widget.setData( 'galleryImage',  el.image);
                                    widget.setData( 'galleryAuthor', el.author);
								}
							});

						}
					}
				]
			}
		]
	};
} );