KindEditor.plugin('gallery', function(K) {
	var self = this, name = 'gallery', lang = self.lang(name + '.');
	self.plugin.gallery = {
		edit : function() {
			var html = ['<div style="padding:20px;">',
					'<div class="ke-dialog-row">',
					'<label for="keAid">' + lang.aid + '</label>',
					'<input class="ke-input-text" type="text" id="keAid" name="aid" value="" style="width:100px;" readonly /> &nbsp;',
					'<span class="ke-button-common ke-button-outer">',
					'<input type="button" class="ke-button-common ke-button" name="selfGallery" value="' + lang.self + '" />',
					'</span> &nbsp;',
					'<span class="ke-button-common ke-button-outer">',
					'<input type="button" class="ke-button-common ke-button" name="articleGallery" value="' + lang.select + '" />',
					'</span>',
					'<br><br><span style="color:gray">' + lang.intro + '</span>',
					'</div>',
					'</div>'].join('');
			var dialog = self.createDialog({
				name : name,
				width : 370,
				title : self.lang(name),
				body : html,
				yesBtn : {
					name : self.lang('yes'),
					click : function(e) {
						var aid = K.trim(aidBox.val());
						if (!/^\d*$/.test(aid)) {
							alert(lang.invalidAid);
							aidBox[0].focus();
							return;
						}
						var html = (aid == '') ? '{saxue_gallery}' : '{saxue_gallery_' + aid + '}';
						self.insertHtml(html).hideDialog().focus();
					}
				}
			});
			var div = dialog.div,
				selfGalleryBtn = K('[name="selfGallery"]', div),
				articleGalleryBtn = K('[name="articleGallery"]', div),
				aidBox = K('input[name="aid"]', div);

			selfGalleryBtn.click(function(e) {
				aidBox.val('');
			});

			articleGalleryBtn.click(function(e) {
				self.loadPlugin('gallerymanager', function() {
					self.plugin.gallerymanagerDialog({
						clickFn : function(aid) {
							if (self.dialogs.length > 1) {
								K('[name="aid"]', div).val(aid);
								self.hideDialog();
							}
						}
					});
				});
			});

			var img = self.plugin.getSelectedGallery();
			if (img) {
				aidBox.val(unescape(img.attr('data-ke-aid')));
			}
			aidBox[0].focus();
			aidBox[0].select();
		},
		'delete' : function() {
			self.plugin.getSelectedGallery().remove();
		}
	};
	self.clickToolbar(name, self.plugin.gallery.edit);
});
