	TJ.Admin.DirectoryTreePanel = Ext.extend(Ext.ux.FileTreePanel, {
		rootText: 'files',		
		rootPath: '#+#+#+#',
//		topMenu: true,
		expandOnRender: false,
		frame: false,
		fileText: 'Directory',
		autoScroll:true,
		url:"/en/filemanager:dirs",
		enableUpload:false,
		enableOpen: false,
		showStatus: true,
		initComponent: function(){




//			this.rootText=this.rootPath;

			this.reloadBtn = new Ext.Toolbar.Button({
							tooltip: 'Reload',
							iconCls: 'icon-refresh',
							cmd: 'reload',
		                    disabled:true,
							handler: this.doCommand,
							scope: this
						});

			this.expandBtn = new Ext.Toolbar.Button({
							toolTip: 'Expand All',
							iconCls: 'icon-expand-all',
							cmd: 'expand',
		                    disabled:true,
							handler: this.doCommand,
							scope: this
						});
			this.collapseBtn = new Ext.Toolbar.Button({
							toolTip: 'Collapse All',
							iconCls: 'icon-collapse-all',
							cmd: 'collapse',
		                    disabled:true,
							handler: this.doCommand,
							scope: this
						});

			this.renameBtn = new Ext.Toolbar.Button({
							text: 'Rename',
							iconCls: 'icon-pencil',
		                    disabled:true,
							cmd: 'rename',
							handler: this.doCommand,
							scope: this
						});

			this.deleteBtn = new Ext.Toolbar.Button({
							text: 'Delete',
							iconCls: 'icon-cross',
		                    disabled:true,
							cmd: 'delete',
							handler: this.doCommand,
							scope: this
						});

			this.newBtn = new Ext.Toolbar.Button({
							text: 'New',
							iconCls: 'icon-folder-add',
		                    disabled:true,
							cmd: 'newdir',
							handler: this.doCommand,
							scope: this
						});

			this.tbar=[this.reloadBtn,this.expandBtn, this.collapseBtn,'-',this.renameBtn, this.deleteBtn,'-',this.newBtn];
			if (this.showStatus)
				this.bbar =  new Ext.StatusBar({    defaultText: ''});

			TJ.Admin.DirectoryTreePanel.superclass.initComponent.call(this);
			this.getRootDirInfo();
			this.on('newdir',function(tree,node){
				console.log('New Dir',node);

			});
			this.getSelectionModel().on('selectionchange',function(sm,node) {
				var valid=true;
				if(node) {

					var path = node.getPath("text").substring(1);
					if(this.showStatus)
						this.getBottomToolbar().setStatus('Directory:  <b>' + path + '</b>');

					if ( (path == 'files') ||
					     (path == 'files/user') ||
					     (path == 'files/secure') )
						valid=false;
					if(node == this.getRootNode())
						valid=false;
				} else {
					valid=false;
				}
				this.reloadBtn.setDisabled(!node || node.isLeaf());
				this.expandBtn.setDisabled(!node || node.isLeaf());
				this.collapseBtn.setDisabled(!node || node.isLeaf());
				this.newBtn.setDisabled(!node);

				this.renameBtn.setDisabled(!valid );
				this.deleteBtn.setDisabled(!valid);
			},this);

		},
		getRootDirInfo: function(){
			var params ={ cmd: 'info'
						};
			var options = {
				 url: this.url,
				 scope: this,
				 params:{cmd: 'info'},
				 callback: this.rootCallback
				};
			Ext.Ajax.request(options);
		},
		rootCallback:function(options, success, response) {
			o = Ext.decode(response.responseText);
			this.getRootNode().setText(o.path);
			this.getRootNode().attributes.path = o.path;
			this.callbackComplete=true;
			this.postRender();

		},
		doCommand: function(btn){
			var node = this.getSelectionModel().getSelectedNode();
			this.onContextClick({node: node},btn);
		},
		render: function(){
	        TJ.Admin.DirectoryTreePanel.superclass.render.apply(this, arguments);
			this.renderComplete=true;
			this.postRender();
		},
		postRender: function(){
			if(this.renderComplete && this.callbackComplete) {
				this.getRootNode().expand();
//				this.getRootNode().select();
			if(this.initialDir)
				this.setDirectory(this.initialDir);
			else
				this.getRootNode().select();
			}
			return;

//			if(this.initialDir)
//				this.setDirectory(this.initialDir);
//			else
//				this.getRootNode().select();


		},
		getDirectory: function(){
			var node = this.getSelectionModel().getSelectedNode();
			if(node)
				return node.getPath("text").substring(1);
			return null;
		},
		setDirectory: function(dir){
			this.expandPath('/'+dir,'text', function(bSuccess,oLastNode) {
				if(oLastNode)
						oLastNode.select();
			});
		}
	});

TJ.Admin.DirectorySelectWindow = Ext.extend(Ext.Window, {
	width: 300,
                constrainHeader:true,				
	height: 500,
	modal: true,
	layout: 'fit',
	title: 'Select Directory',
	closeAction: 'hide',
	initComponent: function() {
//		console.log('dsw id',this.initialDir);
		this.tree = new TJ.Admin.DirectoryTreePanel({initialDir: this.initialDir});
		this.items=this.tree;
//		this.tree.on('dblclick', function(node,e){ this.select(); }, this);
		this.tree.getSelectionModel().on('selectionchange',function(sm,node){
			this.selBtn.setDisabled(node ===null);},this);

		TJ.Admin.DirectorySelectWindow.superclass.initComponent.call(this);
		this.addEvents('select');

			this.selBtn = new Ext.Button({
						text: 'Select',
	                    disabled:true,
						handler: this.select,
						scope: this
					});

			this.closeBtn = new Ext.Button({ text: 'Close', handler: function(){ this.hide(); }, scope: this });

		this.buttons = [this.selBtn, this.closeBtn];


	},
	select: function() {
		this.fireEvent('select', this.tree.getDirectory());
	}
});


TJ.Admin.FileGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
					mode:'manager',
					loadMask: true,
					url:"/en/filemanager:dirs",
					viewConfig:{ autoFill: false, forceFit: false},
					errorText: 'Error',
					initComponent: function() {
						this.cm = new Ext.grid.ColumnModel([
							{header: "Directory" , sortable: true, dataIndex: 'dir', width: 180, hidden: this.mode =='manager'},
							{header: "Filename", sortable: true, dataIndex: 'name',
							           editor: new Ext.form.TextField({
						               allowBlank: false
							           }),
									   renderer: this.iconRenderer,
									   width: 200
							},
							{header: "Last Modified", sortable: true, renderer: Ext.util.Format.dateRenderer('Y/m/d H:i:s'), dataIndex: 'datelastmodified', width: 120},
							{header: "Size", sortable: true, dataIndex: 'size', renderer: TJ.HumanFileSize, align: 'right', width: 60}
						]);
						this.sm = new Ext.grid.RowSelectionModel({singleSelect: true});
						this.sm.on('rowselect',function(sm,row){this.rowIndex=row;},this);

						this.store = new Ext.data.JsonStore({
							url: (this.mode=='manager') ? "/en/filemanager:files" : "/en/filemanager:review",
							root:   'data',
//							id:		'name',
							fields:["name","datelastmodified","size","ext","dir"]
						});
						this.directory=null;
					this.reloadBtn = new Ext.Toolbar.Button({
							tooltip: 'Reload',
							iconCls: 'icon-refresh',
							cmd: 'reload',
							handler: this.doReload,
							scope: this
						});
					this.openBtn = new Ext.Toolbar.Button({
							text: 'Open',
							tooltip: 'Open in new window',
							iconCls: 'icon-open',
		                    disabled:true,
							handler: this.doOpen,
							scope: this
						});
					this.downloadBtn = new Ext.Toolbar.Button({
							text: 'Download',
							tooltip: 'Download this file',
							iconCls: 'icon-open-download',
		                    disabled:true,
							handler: this.doDownload,
							scope: this
						});


						this.renameBtn = new Ext.Toolbar.Button({
							text: 'Rename',
							iconCls: 'icon-pencil',
		                    disabled:true,
							handler: this.startRename,
							scope: this
						});

						this.deleteBtn = new Ext.Toolbar.Button({
							text: 'Delete',
							iconCls: 'icon-cross',
		                    disabled:true,
							handler: this.doDelete,
							scope: this
						});
						this.publishBtn = new Ext.Toolbar.Button({
							text: 'Publish',
							iconCls: 'icon_application_lightning',
		                    disabled:true,
							handler: this.doPublish,
							scope: this
						});

						this.sm.on('selectionchange',function(sm){
							this.renameBtn.setDisabled(sm.getCount()!=1);
							this.deleteBtn.setDisabled(sm.getCount()!=1);
							this.openBtn.setDisabled(sm.getCount()!=1);
							this.downloadBtn.setDisabled(sm.getCount()!=1);
							this.publishBtn.setDisabled(sm.getCount()!=1);

							if(sm.getCount()==1) {
								var str= this.getFilename();
								this.publishBtn.setText((str.substr(str.length-7,str.length)=='.review') ? 'Publish':'Unpublish');
							}
						},this);


						this.tbar=[this.reloadBtn,this.openBtn, this.downloadBtn,'-',this.renameBtn,this.deleteBtn, this.publishBtn];



						TJ.Admin.FileGridPanel.superclass.initComponent.call(this);
						this.store.on({
								update: {scope: this, fn: this.recordUpdate}});

						
						
					},
					iconRenderer: function(name, p,record){
						return '<div class="file-' + record.data.ext + '" style="background: no-repeat; padding-left: 20px;">' + name + '</div>';
					},
	
					getFilename: function() {
						var record = this.selModel.getSelected();
						if(record) {
							return record.data.dir + '/' + record.data.name;
						}
						return null;
					},
					getStatus: function(){
							var count = this.store.getTotalCount();
				            var msg = count === 0 ?
			                'No files to display' :
			                String.format('Displaying {0} files', count);
							return msg;

						},
					doOpen: function(){
						var url = '/en/filemanager:preview?file=' + escape(this.getFilename());
						window.open(url);
					},
					doDownload: function() {
						var url = '/en/filemanager:download?file=' + escape(this.getFilename());
						window.open(url);

					},
					doReload: function(){
						this.store.reload();
					},
					doPublish: function(){
						var record = this.selModel.getSelected();
						if(record) {
							var str = record.data.name;
							if(str.substr(str.length-7,str.length)=='.review')
								record.set('name',str.substr(0,str.length-7));
							else
								record.set('name',str + '.review');
						}
					},
					doDelete: function(){
						var rec= this.getSelectionModel().getSelected();
							Ext.Msg.show({
							   title:'Please confirm',
							   width: 300,
							   msg: 'Are you sure you want to delete this file?<BR> ' + rec.data.dir +'/'+rec.data.name,
							   buttons: Ext.Msg.YESNO,
							   scope: this,
							   fn: function(btn){ if(btn=='yes') {
									var params ={ cmd: 'delete',
												  file: rec.data.dir+'/'+rec.data.name};
									var options = {
										 url: this.url,
										 record: rec,
										 scope: this,
										 params:params,
										 callback: this.cmdCallback
										};
									Ext.Ajax.request(options);
								 }
							   },
							   icon: Ext.MessageBox.QUESTION
							});


					},
					startRename: function(){
		                this.startEditing(this.rowIndex, 0);
					},
					recordUpdate: function(store, record, operation){
						if(operation != Ext.data.Record.EDIT)
							return;

						var	params={	cmd:'rename',
										oldname: record.data.dir+'/'+record.modified.name,
										newname: record.data.dir+'/'+record.data.name};

						var options = {
							 url: this.url,
							 record: record,
							 scope: this,
							 params:params,
							 callback: this.cmdCallback
							};
						Ext.Ajax.request(options);
//						console.log(record);

					},
					cmdCallback:function(options, success, response) {
						// process Ajax success
						if(true === success) {

							// try to decode JSON response
							try {
								o = Ext.decode(response.responseText);
							}
							catch(ex) {
								this.showError(response.responseText);
							}
							if(true === o.success) {
								switch(options.params.cmd) {
									case 'rename':
										options.record.commit();

										break;
									case 'delete':
										this.store.remove(options.record);
										break;
									default: break;
								}
							}
							else {
								switch(options.params.cmd) {
									case 'rename':
										options.record.reject();
									break;
									case 'delete':
									break;
									default:
										break;
								}
								this.showError(o.error || response.responseText);
							}
						}
						else {
							this.showError(response.responseText);
						}
					},



					render: function(ct,position) {
						TJ.Admin.FileGridPanel.superclass.render.call(this, ct, position);
						if(this.mode=='review')
							this.store.load();
						if(this.initialDir)
							this.setDirectory(this.initialDir);

					},
					setDirectory: function(directory) {
						if(this.mode=='manager') {
							this.store.baseParams={path:directory};
							this.store.load();
							this.directory=directory;
						}
					},
					getDirectory: function(){
						return this.directory;

					}
				,showError:function(msg, title) {
					Ext.Msg.show({
						 title:title || this.errorText
						,msg:Ext.util.Format.ellipsis(msg, this.maxMsgLen)
						,fixCursor:true
						,icon:Ext.Msg.ERROR
						,buttons:Ext.Msg.OK
						,minWidth:1200 > String(msg).length ? 360 : 600
					});
				} // eo function showError

});

	TJ.Admin.FileUploadPanel = Ext.extend(Ext.ux.UploadPanel, {
		url:"/en/filemanager:dirs"
		,maxFileSize:16777216
		,initComponent: function(){
			TJ.Admin.FileUploadPanel.superclass.initComponent.call(this);
			this.uploader.progressUrl='/en/filemanager:progress';
		}
	});


	TJ.Admin.FilePreviewPanel = Ext.extend(Ext.Panel,{
//		title: 'Preview File',
		layout: 'fit',
		initComponent: function() {
			this.previewId= Ext.id();
			this.items =
				[{
                    xtype: 'iframepanel',
                    id: this.previewId,
                    loadMask: false,
                    autoShow: true,
                    layout: 'fit'
                }];
			TJ.Admin.FilePreviewPanel.superclass.initComponent.call(this);

		},
		setFile: function(file) {
			if (! this.ownerCt.collapsed)
			{
				Ext.getCmp(this.previewId).setSrc('/en/filemanager:preview?file=' + escape(file));
				this.ownerCt.setTitle('Preview <B>' + file + '</B>');
			}
		}
	});

TJ.Admin.FileManagerPanel = Ext.extend(Ext.Panel, {
	layout: 'border',
	mode : 'manager',
	initComponent: function(){


		this.FilePreviewPanel = new TJ.Admin.FilePreviewPanel();
		this.FileGridPanel = new TJ.Admin.FileGridPanel({showStatus:false, mode: this.mode});
		if(this.mode == 'manager') {
			this.DirTreePanel = new TJ.Admin.DirectoryTreePanel({showStatus:false, initialDir : this.initialValue});
			this.FileUploadPanel = new TJ.Admin.FileUploadPanel();	

		
			this.DirTreePanel.getSelectionModel().on('selectionchange',function() {this.FileUploadPanel.setPath(this.DirTreePanel.getDirectory());
																	  this.FileGridPanel.setDirectory(this.DirTreePanel.getDirectory());
																		this.getBottomToolbar().setStatus('Directory:  <b>' + this.DirTreePanel.getDirectory() + '</b>');
																 	 },this);
		
			this.FileUploadPanel.on('allfinished',function(){ this.FileGridPanel.store.reload();},this);		
		
		}




		this.FileGridPanel.getSelectionModel().on('selectionchange', function(sm){ 
			if(sm.getCount()>0){
				this.getBottomToolbar().setStatus('File:  <b>' + this.FileGridPanel.getFilename() + '</b>');
				this.FilePreviewPanel.setFile(this.FileGridPanel.getFilename());


			}
		},this);
			

		if(this.mode == 'manager') {

		this.items = [ { region: 'west',
						 layout: 'fit',
						 items: this.DirTreePanel,
						 width: 272,
 						 split: true,
						 frame: false
						},
						{	region: 'center',
							layout: 'fit',
							items: this.FileGridPanel,
							frame: false
						},
						{ region: 'east',
							width: 200,
							split: true,
							frame: false,
  							layout: 'fit',
							title:'Upload',
						  collapsible: true,
						  collapsed: this.selectfile,
							items: this.FileUploadPanel
						},
						{ region: 'south',
						  height: 200,
						  split: true,
						  frame: false,
						  layout: 'fit',
						  title: 'Preview File',
						  collapsible: true,
						  collapsed: false,//this.selectfile,
						  items: this.FilePreviewPanel
						  }];
		}else{
		this.items = [ 	{	region: 'center',
							layout: 'fit',
							items: this.FileGridPanel,
							frame: false
						},
						{ region: 'south',
						  height: 200,
						  split: true,
						  frame: false,
						  layout: 'fit',
						  title: 'Preview File',
						  collapsible: true,
						  collapsed: this.selectfile,
						  items: this.FilePreviewPanel
						  }];
		}

		this.bbar =  new Ext.StatusBar({defaultText: ''});
		TJ.Admin.FileManagerPanel.superclass.initComponent.call(this);
//		this.items=[];
	},
	getSelectedFilename: function() {
		return this.FileGridPanel.getFilename();
	}

});

Ext.reg('tjadmin_filemanagerpanel',TJ.Admin.FileManagerPanel);

	TJ.Admin.FileSelectWindow = Ext.extend(Ext.Window,{
		width: 800,
		height: 500,
                constrainHeader:true,				
		modal: true,
		layout: 'fit',
		title: 'Select File',
		closeAction: 'hide',
		callback: null,
		initComponent: function() {
			this.fm = new TJ.Admin.FileManagerPanel({selectfile:true,initialValue: this.initialValue});
			this.items =this.fm;
			TJ.Admin.FileSelectWindow.superclass.initComponent.call(this);

			this.fm.FileGridPanel.selModel.on('selectionchange', function(sm){ this.selBtn.setDisabled(sm.getCount()===0);},this);

			this.addEvents('select');
			this.selBtn = new Ext.Button({
						text: 'Select',
	                    disabled:true,
						handler: this.select,
						scope: this
					});

			this.closeBtn = new Ext.Button({ text: 'Close', handler: function(){ this.hide(); }, scope: this });

		this.buttons = [this.selBtn, this.closeBtn];

		},
		show: function(callback){
			if(callback)
				this.callback=callback;
			TJ.Admin.FileSelectWindow.superclass.show.call(this);
		},
		select: function() {
//			console.log(this.fm.getSelectedFilename());
			this.fireEvent('select', this.fm.getSelectedFilename());
			if(this.callback) {
				this.hide();
				this.callback(this.fm.getSelectedFilename());
				this.callback=null;


			}
		}
	});