dojo.provide("epages.cartridges.de_epages.mediagallery.widget.Filebrowser");
dojo.require("epages.widget.LocalizedWidget");
dojo.require('epages.cartridges.de_epages.mediagallery.widget.Imagedbstore');
epages.require('ep_shop_tree', 'epages.cartridges.de_epages.mediagallery.widget.Imagedbtree');
dojo.require('epages.widget.Elementlist');
dojo.require("epages.cartridges.de_epages.mediagallery.widget.Filelistitem");
dojo.require("epages.widget.Dialog");
dojo.require("epages.cartridges.de_epages.mediagallery.widget.Filestore");
dojo.require("epages.cartridges.de_epages.mediagallery.widget.Filetree");
dojo.require("epages.widget.Tooltip");
dojo.require('epages.string');
dojo.require('epages.html');
dojo.require('epages.browser');
epages.require('ep_shop_upload', 'epages.uploader');

(function(jq){

	var jqUploaderReady = !1,
		jqUploaderCreate = function( self, data, exists, callback ){
			de_epages(self.uploadNode)
				.presentationUiUploader({
					data:		data,
					exists:		exists,
					big:		true,
					multiple:	true,
					callback:	callback
				});
		};

	dojo.declare (
		"epages.cartridges.de_epages.mediagallery.widget.Filebrowser",
		[epages.widget.LocalizedWidget],
		{
			/**
			 * public properties
			 */
			siteId          : epages.vars.SiteID,		// Integer - epages SiteID
			url             : '?',						// String - request url
			directory       : 'MediaGallery',			// String - base directory
			multiSelect     : 'true',					// String - multi item selection on or off
			validFileTypes  : '',						// String - show only files with these extensions
			imageDB         : epages.vars.ImageDbRoot,	// String - url to image database
			cssClass        : '',						// String - additional css classes
			opener          : '',						// String - define from where it was opend, is passed to the plugins

			multiSelectString   : "", 					// String - save multiSelect as string ("true" or "false")
			_fileStore          : undefined,			// Object - reference to file store
			_eventHandles       : undefined,			// Object[]- save event connects temporary for oneLineValueNode in this array
			_plugins            : {},					// save loaded plugins and depending nodes
			_visibleLeftBar     : undefined,
			_visibleContent     : undefined,
			_currentActivePlugin: undefined,

			galleryUsage        : {},               // hash with gallery size usage data

			/**
			 * dojo widget properties
			 */

			templatePath     : dojo.moduleUrl('epages.cartridges.de_epages.mediagallery.widget','templates/Filebrowser.html'),
			translationName  : dojo.moduleUrl('epages.cartridges.de_epages.mediagallery.widget','templates/translation'),
			widgetsInTemplate:true,

			/**
			 * widget life cycle
			 */

			postMixInProperties: function() {
			// summary: initalize values - adjust properites
				this.inherited("postMixInProperties", arguments);
				this.multiSelect = epages.string.toBoolean(this.multiSelect);
				this.multiSelectString = this.multiSelect ? "true" : "false";
			},

			setFileTypes: function(/* String */ fileTypes) {
				if(typeof(fileTypes) === "string" && (this.validFileTypes != fileTypes)) {
					this.validFileTypes = fileTypes;
					this._fileStore.setFileTypes(this.validFileTypes);
					this.fileTreeWidget.reloadFiles();
				}
			},

			postCreate: function() {
			// summary: initalize widget - append events, adjust properites
				this.inherited("postCreate", arguments);

				this._appendEvents();

				this._fileStore = (eval(this.id+'Filestore'));
				this._eventHandles = [];

				// gallery usage updater
				this.galleryUsage = this._fileStore.galleryUsage;

				// action event for upload button
				this._changeUploader();

				//register and build plugin connections
				this._registerPlugins();

				//### DEBUG ###

				//### DEBUG ###
			},

			startup: function() {
			// summary: load files of base folder
				this.inherited("startup", arguments);
				this.openRootFolder();
			},

			_appendEvents: function() {
			// summary: register events and subscriptions

				// register events
				this.connect(this.newFolderButtonNode, 'onclick', '_OnNewFolder');
				this.connect(this.renameFolderButtonNode, 'onclick', '_OnRenameFolder');
				this.connect(this.deleteFolderButtonNode, 'onclick', '_OnDeleteFolder');
				this.connect(this.deleteFilesNode, 'onclick', '_OnDeleteFiles');
				this.connect(this.copyDBImagesNode, 'onclick', '_OnCopyFilesFromDB');
				this.connect(this.oneLineValueNode,'onchange', '_removeDialogErrorLineValueNode');
				this.connect(this.oneLineValueNode,'onkeyup', '_removeDialogErrorLineValueNode');
				this.connect(this.selectImageDbNode,'onclick', '_showImageDb');
				this.connect(this.selectMediagalleryNode,'onclick', '_showMediagallery');


				// subscriptions
				dojo.subscribe(this.uploadNode.id + '/onUploadFinished', this, '_OnUploadFinish');	// upload finished
				dojo.subscribe(this.fileTreeWidget.id + '/select', this, '_OnSelectFileTree');				// directory selected
				dojo.subscribe(this.imagedbTreeWidget.id + '/select', this, '_OnSelectDB');						// imagedb directory selected
				dojo.subscribe(this.fileListWidget.id + '/select', this, '_OnSelectFileList');				// file in file list selected
				dojo.subscribe(this.id + 'Filelist/afterSetChildren', this, "_onFileListCreated");		// items in filelist ready
				dojo.subscribe(this.fileListWidget.store.id + '/onError', this, '_OnError');					// error in file store
				dojo.subscribe(this.fileListWidget.store.id + '/onSuccess', this, '_OnSuccess');			// fixed error in file store

				dojo.subscribe(this.fileListWidget.store.id + '/updateCurrentBytes', this, function(kilobytes) {
					dojo.publish(this.id+'/updateCurrentBytes', [kilobytes]);
				});

				dojo.subscribe('Filebrowser/showMediagallery',this,'showMediagallery');
				dojo.subscribe('Filebrowser/showMediagalleryContent',this,'showMediagalleryContent');
				dojo.subscribe('Filebrowser/showMediagalleryLeftBox',this,'showMediagalleryLeftBox');
			},

			/**
			 * getter, setter and other public functions
			 */

			openRootFolder: function() {
			// summary: simulate click on root node
				this.fileTreeWidget.onClick(this.fileTreeWidget.rootNode.item, this.fileTreeWidget.rootNode);
			},

			getSelectedItems : function() {
			// summary: get selected items
			// returns: selected items of file list
				return $$(this.id + 'Filelist').selectedNodes();
			},

			/**
			 * events and subscriptions
			 */

			_onFileListCreated: function(/* object */ opt) {
			// summary: attach button events to file items
			// opt: { source: this, length: elements.length }

				for( var i=0,iLength=opt.length ; i<iLength ; i++ ) {
					var curChild = opt.source.children[i];

					// attach delete button event
					if(curChild.canDelete && curChild.deleteNode) {
						this.connect(curChild.deleteNode, "onclick", "_OnDeleteFilesInline");
						curChild.deleteNode.style.display="";
					}

					// attach download button event
					if(curChild.downloadNode) {
						dojo.connect(curChild.downloadNode, "onmouseup", curChild, "_onDownload");

						curChild.downloadNode.style.display="";
						curChild.downloadNode.href=curChild.fullpath;
						curChild.downloadNode.onclick=function() {
							return false;
						};
					}
				}
			},

			_removeDialogErrorLineValueNode: function(){
			// summary: event function (keyup change, oneLineValueNode) -remove css error class and error message from onLineValueNode
				dojo.publish("uimessage/hide");
				dojo.removeClass(this.oneLineValueNode,'DialogError');
			},

			/**
			* widget button/ display functions
			*/

			_replaceDirectoryName: function(/* string */ directoryName) {
			// summary: replaces "MediaGallery" and "ImageDb" with translations
				if(directoryName) {
					directoryName=directoryName.replace(/^MediaGallery/, this.translate("MediaGallery"));
					directoryName=directoryName.replace(/^ImageDb/, this.translate("ImageDb"));
				}
				return directoryName;
			},

			_setCurrentDirectory: function(/* object */ opt) {
			// summary: updates the currentDirectoryNode (insert current directory)
				var directoryName = this._replaceDirectoryName(opt.currentDirectory);
				if(directoryName){
					this.currentDirectoryNode.firstChild.data = directoryName;
				}
				else{
					this.currentDirectoryNode.firstChild.data = this.translate("MediaGallery");
				}
			},

			_showImageDb: function() {
				dojo.fx.slideTo({ node: this.imageDbAreaNode, left:"0", top:"0", unit:"px" }).play();
				this._visibleLeftBar = this.imageDbAreaNode;
				this._currentActivePlugin = 'ImageDB';
			},

			_showMediagallery: function() {
				if(this._currentActivePlugin){
					this._currentActivePlugin = undefined;
				}
				if(this._visibleLeftBar){
					dojo.fx.slideTo({ node: this._visibleLeftBar, left:"-230", top:"0", unit:"px" }).play();
				}
				this.openRootFolder();
			},
			_showMediagalleryContent: function(){
				if(this._currentActivePlugin){
					this._currentActivePlugin = undefined;
				}
				if(this._visibleContent){
					dojo.fx.slideTo({ node: this._visibleContent, left:"680", top:"0", unit:"px" }).play();
				}
			},

			showMediagallery: function(){
				this._showMediagallery();
				this._showMediagalleryContent();
			},

			showMediagalleryLeftBox: function(){
				this._showMediagallery();
			},

			showMediagalleryContent: function(){
				this._showMediagalleryContent();
			},

			changeOpener: function(opener){
				this.opener = opener;
				dojo.publish('Filebrowser/changeOpener',[opener]);
			},

			_selectFileByName: function(fileName){
				var selectedFile;
				var fileListChildren = this.fileListWidget.children;
				for (var i = 0, l = fileListChildren.length; i < l; i++) {
					if (fileListChildren[i].name == fileName){
						selectedFile = fileListChildren[i];
						break;
					}
				}
				this.fileListWidget.select(selectedFile);
			},

			/**
			* file / folder operations
			*/

			/*  --- NEW FOLDER --- */
			_OnCancelSingleDialog: function (/* event */ evt) {
			// summary: reset function of oneLineValueNode
			// description: resets value, hides the node and removes all connected events
				this.oneLineFormNode.style.display="none";
				this.oneLineValueNode.value="";
				this.newFolderButtonNode.parentNode.style.display="";
				for( var i=0,iLength=this._eventHandles.length ; i<iLength ; i++ ){
					dojo.disconnect(this._eventHandles[i]);
				}
				this._eventHandles = [];
			},

			_OnSaveNewFolder: function(/* event */ evt) {
			// summary: creates a new directory
				if(this.oneLineValueNode.value == ''){
					this._showErrorBubble(this.translate('InsertNewFolderName'));
				} else {
					if(this.fileTreeWidget.createDirectory(this.oneLineValueNode.value) == true) {
						// show buttons, close dialog
						this._OnCancelSingleDialog(evt);
					}
				}
			},

			_OnNewFolderKeyUp: function(/* event */ evt) {
			// summary: event function (keyup, oneLineFormNode) - trigger save function if enter key was pressed
				if(evt.keyCode == 13) {		// enter pressed
					this._OnSaveNewFolder(evt);
				}
			},

			_OnNewFolder: function(/* event */ evt) {
			// summary: event function (onclick, newFolderButtonNode) - initalize elements of "oneLineForm" (form to create a new folder)
				var directory = this.fileTreeWidget.getCurrentDirectory();
				if (directory === undefined) {
					console.warn('_OnNewFolder() -> directory undefined in '+this.declaredClass);
				} else {
					this.newFolderButtonNode.parentNode.style.display="none";
					this.oneLineFormNode.style.display="";
					this.oneLineTextNode.innerHTML=this.translate('NewFolder');
					this.oneLineValueNode.focus();
					this._eventHandles.push(dojo.connect(this.oneLineFormNode,   'onkeyup', this, '_OnNewFolderKeyUp'));
					this._eventHandles.push(dojo.connect(this.oneLineSaveNode,   'onclick', this, '_OnSaveNewFolder'));
					this._eventHandles.push(dojo.connect(this.oneLineCancelNode, 'onclick', this, '_OnCancelSingleDialog'));
				}
			},

			/*  --- DELETE FOLDER --- */
			_OnDeleteFolder: function (/* event */ evt) {
			// summary: event function (click, deleteFolderButtonNode) - delete current directory
				var directory = this.fileTreeWidget.getCurrentDirectory();
				if (directory === undefined) {
					console.warn('_OnDeleteFolder() -> directory undefined in '+this.declaredClass);
				} else {
					var folderName = this.fileTreeWidget.getCurrentDirectoryName();
					// show confirmation message
					dojo.require("epages.uimessagehandler");
					dojo.publish("uimessage/show", [
						this.translate("HeadLineDeleteFolder"),
						this.translate("DeleteFolderAndSubFolder")+" <br />"+this.translate("SelectedFolder") + ': ' + folderName, 'Dialog', {
							titleBar:  this.translate("DeleteFolder"),
							sizeClass: 'Large',
							typeClass: 'Confirmation',
							onYes:     dojo.hitch(this, function() {
								this.fileTreeWidget.deleteDirectory(directory);
							})
						}]);
				}
			},

			/*  --- RENAME FOLDER --- */
			_OnSaveRenameFolder: function (/* event */ evt) {
			// summary: event function (click, renameFolderButtonNode) - rename current directory
				// save
				if(this.fileTreeWidget.renameDirectory(this.oneLineValueNode.value) == true) {
					// show buttons, close dialog
					this._OnCancelSingleDialog(evt);
				}
			},

			_OnRenameFolderKeyUp: function(/* event */ evt) {
			// summary: event function (keyup, oneLineFormNode) - trigger save function if enter key was pressed
				if(evt.keyCode == 13) {
					this._OnSaveRenameFolder(evt);
				}
			},

			_OnRenameFolder: function (/* event */ evt) {
			// summary: event function (click, renameFolderButtonNode) - initalize elements of "oneLineForm" (form to rename current folder)
				var directory = this.fileTreeWidget.getCurrentDirectory();
				if (directory === undefined) {
					console.warn('_OnRenameFolder() -> directory undefined in '+this.declaredClass);
				} else {
					var node = this.fileTreeWidget.getLastSelectedNode();
					this.newFolderButtonNode.parentNode.style.display="none";
					this.oneLineFormNode.style.display="";
					this.oneLineTextNode.innerHTML=this.translate('RenameFolder');
					this.oneLineValueNode.value = node.labelNode.innerHTML;
					this.oneLineValueNode.focus();
					this._eventHandles.push(dojo.connect(this.oneLineFormNode,   'onkeyup', this, '_OnRenameFolderKeyUp'));
					this._eventHandles.push(dojo.connect(this.oneLineSaveNode,   'onclick', this, '_OnSaveRenameFolder'));
					this._eventHandles.push(dojo.connect(this.oneLineCancelNode, 'onclick', this, '_OnCancelSingleDialog'));
				}
			},


			/*  --- COPY FILES FROM DB TO MediaGallery --- */
			_OnCopyFilesFromDB: function (/* event */ evt) {
			// summary: event function (click, copyDBImagesNode) - copies selected files to last selected dir in mediagallery
				var directory = this.fileTreeWidget.getCurrentDirectory();
				if (directory === undefined) {
						alert(this.translate('NoDirectorySelected'));
				} else {
					var files = this.fileListWidget.selectedItems();
					if (files.length > 0) {
						this._fileStore.copyImageFromImageDb(directory, files);
						var treeNodeWidget =this.fileTreeWidget.getLastSelectedNode();
						epages.event.fire(treeNodeWidget.domNode, "click");
						this._showMediagallery();
						//select last copied image
						for(var i = 0, l = files.length; i < l; i++){
							var currentFile = files[i];
							var currentFileName = currentFile.substring(currentFile.lastIndexOf("/")+1);
							//select file in current Filelist
							this._selectFileByName(currentFileName);
						}
					} else {
						dojo.publish("uimessage/show", [ this.translate('NoFilesSelected'), this.translate('DoSelectFiles'), 'Dialog', {
								titleBar: this.translate('FileRepository')+" &ndash; "+this.translate('Notification'),
								typeClass: 'Notification'
							}
						]);
					}
				}
			},

			_OnDeleteFilesInline: function(evt) {
			// summary: display confirmation dialog

					// look up filename
					var srcNode = evt.currentTarget;
					var node = srcNode;
					while(!node.getAttribute("widgetid") && node.parentNode !== undefined) {
						node = node.parentNode;
					}

					var fileName = "";
					var widgetId = undefined;

					if(node) {
						widgetId = node.getAttribute("widgetid");
					}
					if(widgetId) {
						var fileWidget = $$(widgetId);

						// show confirmation message
						dojo.require("epages.uimessagehandler");
						dojo.publish("uimessage/show", [
							this.translate("HeadLineDeleteFile"),
							this.translate("File") + ': ' + fileWidget.name, 'Dialog', {
								titleBar:  this.translate("TitleDeleteFile"),
								sizeClass: 'Large',
								typeClass: 'Confirmation',
								onYes:     dojo.hitch(this, function() {
									this.fileTreeWidget.deleteFiles();
								})
						}]);
					}
			},

			_OnDeleteFiles: function() {
			// summary: delete current selected files
				// lookup filenames
				var fileNames = $A([]);
				var deleteTotalSize = 0;
				$A(this.fileListWidget.selectedNodes()).each(function(el) {
					fileNames.push(el.name);
					deleteTotalSize += el.data.size;
				});
				// show confirmation message
				if(fileNames.length) {
					dojo.require("epages.uimessagehandler");
					dojo.publish("uimessage/show", [
						this.translate("HeadLineDeleteFiles"),
						this.translate("Files") + ': ' + fileNames.join(', ') , 'Dialog', {
							titleBar:  this.translate("TitleDeleteFiles"),
							sizeClass: 'Large',
							typeClass: 'Confirmation',
							onYes:     dojo.hitch(this, function() {
								this.fileTreeWidget.deleteFiles();
							})
						}]);
					}
			},

			_changeUploader: function (params) {
				var self = this,
					exists = [],
					data = {
						ViewAction:			'JSONViewResponse',
						ChangeAction:		'UploadFilesToMediaGallery',
						ObjectID:			epages.vars.SiteID,
						handleashtml:		1,
						Directory:			(params && params.directory) ? params.directory : '/'
					},
					callback = function( data ){
						dojo.publish( self.uploadNode.id + '/onUploadFinished', [data] );
						// refresh uploader settings
						self._changeUploader(params);
					};
					
				dojo.forEach( this.fileListWidget._allChildren, function( file, i ){
					exists.push(file.name);
				});

				if( jqUploaderReady ){
						jqUploaderCreate( self, data, exists, callback );
				}
				else{
					jq.ready( 'de_epages.presentation.ui.uploader', function(){
						jqUploaderReady = !0;
						jqUploaderCreate( self, data, exists, callback );
					});
				}
			},

			/*  --- SELECT A TREE NODE --- */
			_OnSelectFileTree: function (/* Object */ opt) {
			// summary: sets the current directory and shows the right action links
			// opt: {node:node, currentDirectory: directory}
				opt.currentDirectory = this._fileStore.removeMediaGalleryFromString(opt.currentDirectory);
				//this.uploadWidget.setDirectory(opt.currentDirectory);
				this._changeUploader({ directory : opt.currentDirectory });
				this._setCurrentDirectory(opt);

				// show possible directory actions
				this.newFolderButtonNode.style.display="";
				this.deleteFilesNode.style.display="";
				var directory = this.fileTreeWidget.getCurrentDirectory();
				if (directory !== undefined && directory != this.directory) {
					this.renameFolderButtonNode.style.display="";
					this.deleteFolderButtonNode.style.display="";
				} else {
					this.renameFolderButtonNode.style.display="none";
					this.deleteFolderButtonNode.style.display="none";
				}

				// hide image db actions
				this.imageDbActionsNode.style.display="none";
				this.uploadNode.style.display="";
				this.copyToTargetNode.firstChild.data = this._replaceDirectoryName(directory);

				// publish event
				dojo.publish(this.id+'/fileTreeNodeSelected', []);

				this._updateMultiselectTip();
			},

			_OnSelectDB: function (opt) {
			// summary: sets the current image db directory and shows the right action links
				this._setCurrentDirectory(opt);

				// hide directory actions
				this.newFolderButtonNode.style.display="none";
				this.renameFolderButtonNode.style.display="none";
				this.deleteFolderButtonNode.style.display="none";
				this.deleteFilesNode.style.display="none";

				// adjust copy button
				if(epages.Browser.engine == "Gecko") {
					this.imageDbActionsNode.style.display="inline";
				}else {
					this.imageDbActionsNode.style.display="";
				}

				// hide upload widget
				this.uploadNode.style.display="none";

				// publish event
				dojo.publish(this.id+'/imageDBSelected', []);

				this._updateMultiselectTip();
			},

			_updateMultiselectTip : function() {
				// summary: show or hide multi select hint
				if(this.multiSelect && this.fileListWidget.children.length > 1) {
					this.MultiselectTipNode.style.display="";
				} else {
					this.MultiselectTipNode.style.display="none";
				}
			},

			_OnSelectFileList: function(opt){
			// summary: subscription to fileListWidget - publish that files
				var tooMuchItemsSelected = (this.multiSelect == false && this.fileListWidget.selectedNodes().length > 1);
				dojo.publish(this.id+'/filesSelected', [tooMuchItemsSelected]);
			},

			_OnUploadFinish: function (/* object*/opt){
			// summary: subscription to upload widget (upload finished) - refresh file list
			// opt: { result: this._filesUploaded }
				var directory = this.fileTreeWidget.getCurrentDirectory();
				this._fileStore.resetDirectory(directory);
				this.fileTreeWidget.reloadFiles();

				if(opt.length > 0) {
					var lastItem = opt[opt.length-1];
					if(lastItem && lastItem.success && lastItem.success.currentGallerySize) {
						dojo.publish(this.id+'/updateCurrentBytes', [lastItem.success.currentGallerySize]);
					}
				}
			},

			_OnError: function(errorData) {
			// summary: subscription to file store widget - display errors
			// errorData: {Errors: JsonData.error.data.Errors}
				for( var i=0,iLength=errorData.Errors.length ; i<iLength ; i++ ) {
					if(errorData.Errors[i].Reason == 'DirectoryAlreadyExists') {
						this._showErrorBubble(this.translate('DirectoryAlreadyExists'));
					}
					else if(errorData.Errors[i].Reason == 'FileAlreadyExists') {
						this._showErrorBubble(this.translate('FileAlreadyExists'), 'store');
					}
					else if(errorData.Errors[i].Reason == 'GeneralDirectoryCreateError') {
						this._showErrorBubble(this.translate('GeneralDirectoryCreateError'));
					}
				}
			},

			_OnSuccess: function(callerData) {
			// summary: hides the error bubble
			// description:
			//   An action resulted in an error in the first place. A second
			//   user action then leads to success, so no more error should be indicated.
				this._hideErrorBubble();
			},

			_showErrorBubble: function(/* string */ captionText, /* string */ elementLocation) {
			// summary:
			//			shows an error bubble below oneLineValueNode
			// description:
			//			Displays an error bubble at the location of the error throwing dom element containing the
			//			given captionText. If the parameter elementLocation is set to 'store' the function displays
			//			the bubble for the file store - otherwise for the directory tree.

				// bubble in directory tree or in file store?
				var targetElement;
				if(elementLocation == 'store') {
					targetElement = this.getSelectedItems()[0].nodeTitle;
				}
				else {
					targetElement = this.oneLineValueNode;
				}

				var position = $E(targetElement).getAbsolutePosition();
				dojo.publish("uimessage/show", ["", captionText, "Bubble", {
					typeClass: "Warning",
					sizeClass: "Small",
					x: position.x,
					y: position.y + targetElement.offsetHeight
				}]);
				dojo.addClass(targetElement,'DialogError');
			},

			_hideErrorBubble: function(targetElement) {
				this._removeDialogErrorLineValueNode();
			},

			_registerPlugins: function(){
				var mediaGalleryPlugins = epages.vars.MediaGalleryPlugins;
				//check if plugins defined
				if(mediaGalleryPlugins && mediaGalleryPlugins.length){
					for(var i = 0,l = mediaGalleryPlugins.length; i < l;i++){
						var currentPlugin = mediaGalleryPlugins[i];
						//insert Plugin link to link section
						var linkNode = document.createElement('div');
						dojo.style(linkNode,'cursor','pointer');
						linkNode.innerHTML = '<img src="'+currentPlugin.link.iconSrc+'" />'+currentPlugin.link.title;
						this.PluginLinksNode.appendChild(linkNode);
						this.connect(linkNode,'onclick', function(){
							this._OnPluginLinkClick(currentPlugin.id);
						});

						//insert leftBarContainer with widget
						var leftBarPluginNode = document.createElement('div');
						leftBarPluginNode.innerHTML = currentPlugin.leftBarWidget;
						dojo.addClass(leftBarPluginNode,'PluginLeftBar');
						this.LeftBarContainerNode.appendChild(leftBarPluginNode);
						dojo.parser.parse(leftBarPluginNode);
						var mediagalleryNode = this.selectMediagalleryNode.cloneNode(true);
						this.connect(mediagalleryNode,'onclick', 'showMediagallery');
						leftBarPluginNode.insertBefore(mediagalleryNode,leftBarPluginNode.firstChild);

						//insert mainContainer with widget
						var contentPluginNode = document.createElement('div');
						contentPluginNode.innerHTML = currentPlugin.contentWidget;
						dojo.addClass(contentPluginNode,'PluginContent');
						this.ContentNode.appendChild(contentPluginNode);
						dojo.parser.parse(contentPluginNode);


						this._plugins[currentPlugin.id] = {
							'pluginData': currentPlugin,
							'linkNode': linkNode,
							'linkNodeOnClickConnect':'',
							'leftBarNode':leftBarPluginNode,
							'contentNode': contentPluginNode
						};
					}
				}
			},

			_OnPluginLinkClick:function(pluginId){
				if(this._plugins[pluginId]){
					var currentPlugin = this._plugins[pluginId];
					dojo.fx.slideTo({ node: currentPlugin.leftBarNode, left:"0", top:"0", unit:"px" }).play();
					this._visibleLeftBar = currentPlugin.leftBarNode;
					dojo.fx.slideTo({ node: currentPlugin.contentNode, left:"0", top:"0", unit:"px" }).play();
					this._visibleContent = currentPlugin.contentNode;
					dojo.publish('Filebrowser/PluginLinkClick',[{id: pluginId,opener: this.opener}]);
					this._currentActivePlugin = pluginId;
				}
			},

			onApply: function(){
				dojo.publish('Filebrowser/onApply',[this._currentActivePlugin]);
				if(this._currentActivePlugin && this._currentActivePlugin == 'ImageDB'){
					//when ImageDB is activated check if there are files selected and copy them to own images and insert them
					if(this.getSelectedItems()){
						this._OnCopyFilesFromDB();
					}
				}
			},

			pluginActive:function(){
				if(this._currentActivePlugin){
					return this._currentActivePlugin;
				}
				else{
					return false;
				}
			}
		}
	);

})(jQuery);