// This javascript class extends functionality found in FileManager.js

var WFMFileManager = new Class({
	Extends: FileManager,
	
	// This extends the FileManager's initialize by adding a logout icon
	initialize:function(options){
		this.parent(options);
		this.logoutIcon = new Element('div', {
			'class': 'filemanager-logout',
			/*title: this.language.close,*/
			events: {click: this.logout.bind(this)}
		}).adopt(new Asset.image(this.options.assetBasePath + 'lock.png')).inject(this.el);
		this.tips.attach(this.logoutIcon.appearOn(this.logoutIcon, [1, 0.8]).appearOn(this.el, 0.8));
	},
	
	// Add a logout function
	logout: function(e){
		this.fireEvent('logout');
		this.hide();
	},
	
	// This function re-implements the fill function and adds support for the customized download
	// This function also removes the 'Icons/' from some image paths.
	fill: function(j, nofade){
		this.Directory = j.path;
		this.CurrentDir = j.dir;
		if (!nofade) this.fillInfo(j.dir);
		this.browser.empty();

		if (!j.files) return;

		var els = [[], []];
		$each(j.files, function(file){
			file.dir = j.path;
			var el = file.element = new Element('span', {'class': 'fi', href: '#'}).adopt(
				new Asset.image(this.options.assetBasePath + file.icon + '.png'),
				new Element('span', {text: file.name})
			).store('file', file);

			var icons = [];
			// WFMEdit: Only show controls if the user has permissions
			if (file.mime!='text/directory') {
				if (this.options.permissions.download) {
					icons.push(new Asset.image(this.options.assetBasePath + 'disk.png', {title: this.language.download}).addClass('browser-icon').addEvent('click', (function(e){
						this.tips.hide();
						e.stop();
					
						// WFMEdit: Invoke the browser's download dialog
						var h = Hash.toQueryString(this.options.uploadAuthData);
						window.open(this.normalize(this.options.url+'?event=download&file='+file.name+'&directory='+this.normalize(this.Directory+'/')+'&format=raw'+'&'+h));
					}).bind(this)).inject(el, 'top'));
				}
			}

			// WFMEdit: Only show controls if the user has permissions
			if (file.name != '..') {
				if (this.options.permissions.destroy) {
					['destroy', 'rename'].each(function(v){
						icons.push(new Asset.image(this.options.assetBasePath + v + '.png', {title: this.language[v]}).addClass('browser-icon').addEvent('click', this[v].bindWithEvent(this, [file])).injectTop(el));
					}, this);
				}
			}

			els[file.mime == 'text/directory' ? 1 : 0].push(el);
			if (file.name == '..') el.set('opacity', 0.7);
			el.inject(new Element('li').inject(this.browser)).store('parent', el.getParent());
			icons = $$(icons.map(function(icon){ return icon.appearOn(icon, [1, 0.7]); })).appearOn(el.getParent('li'), 0.7);
		}, this);

		var self = this, revert = function(el){
			el.set('opacity', 1).store('block', true).removeClass('drag').removeClass('move').setStyles({
				opacity: 1,
				zIndex: '',
				position: 'relative',
				width: 'auto',
				left: 0,
				top: 0
			}).inject(el.retrieve('parent'));
			el.getElements('img.browser-icon').set('opacity', 0);
			
			document.removeEvents('keydown', self.bound.keydown).removeEvents('keyup', self.bound.keydown);
			self.imageadd.fade(0);

			self.relayClick.apply(el);
		};
		
		// WFMEdit: Disable dragging in IE browsers
		if (Browser.Engine.trident == undefined) {
			$$(els[0]).makeDraggable({
				droppables: $$(this.droppables, els[1]),

				onDrag: function(el, e){
					self.imageadd.setStyles({
						left: e.page.x + 15,
						top: e.page.y + 15
					});
				},

				onBeforeStart: function(el){
					self.deselect();
					self.tips.hide();
					var position = el.getPosition();
					el.addClass('drag').setStyles({
						zIndex: self.dragZIndex,
						position: 'absolute',
						width: el.getWidth() - el.getStyle('paddingLeft').toInt(),
						left: position.x,
						top: position.y
					}).inject(self.container);
				},

				onCancel: revert,

				onStart: function(el){
					el.set('opacity', 0.7).addClass('move');
					document.addEvents({
						keydown: self.bound.keydown,
						keyup: self.bound.keyup
					});
				},

				onEnter: function(el, droppable){
					droppable.addClass('droppable');
				},

				onLeave: function(el, droppable){
					droppable.removeClass('droppable');
				},

				onDrop: function(el, droppable, e){
					revert(el);

					if (e.control || e.meta || !droppable) el.setStyles({left: 0, top: 0});
					if (!droppable && !e.control && !e.meta) return;
				
					var dir;
					if (droppable){
						droppable.addClass('selected').removeClass('droppable');
						(function(){ droppable.removeClass('selected'); }).delay(300);
						if (self.onDragComplete(el, droppable)) return;

						dir = droppable.retrieve('file');
					}
					var file = el.retrieve('file');

					new FileManager.Request({
						url: self.options.url + '?event=move',
						data: {
							file: file.name,
							directory: self.Directory,
							newDirectory: dir ? dir.dir + '/' + dir.name : self.Directory,
							copy: e.control || e.meta ? 1 : 0
						},
						onSuccess: function(){
							if (!dir) self.load(self.Directory);
						}
					}, self).post();

					self.fireEvent('modify', [$unlink(file)]);

					if (!e.control && !e.meta)
						el.fade(0).get('tween').chain(function(){
							self.deselect(el);
							el.getParent().destroy();
						});
				}
			});
		}

		$$(els).setStyles({left: 0, top: 0});

		this.tips.attach(this.browser.getElements('img.browser-icon'));
	},
	
	// This function reimplements the default filemanager behavior but removes the 'Icons/' used in some image paths
	fillInfo: function(file, path){
		if (!file) file = this.CurrentDir;
		if (!path) path = this.Directory;

		if (!file) return;
		var size = this.size(file.size);

		this.info.fade(1).getElement('img').set({
			src: this.options.assetBasePath + file.icon + '.png',
			alt: file.mime
		});
		
		this.fireHooks('cleanup');
		this.preview.empty();

		this.info.getElement('h1').set('text', file.name);
		this.info.getElement('dd.filemanager-modified').set('text', file.date);
		this.info.getElement('dd.filemanager-type').set('text', file.mime);
		this.info.getElement('dd.filemanager-size').set('text', !size[0] && size[1] == 'Bytes' ? '-' : (size.join(' ') + (size[1] != 'Bytes' ? ' (' + file.size + ' Bytes)' : '')));
		this.info.getElement('h2.filemanager-headline').setStyle('display', file.mime == 'text/directory' ? 'none' : 'block');

		var text = [], pre = [];

		path.split('/').each(function(v){
			if (!v) return;

			pre.push(v);
			text.push(new Element('a', {
					'class': 'icon',
					href: '#',
					text: v
				}).addEvent('click', (function(e, dir){
					e.stop();

					this.load(dir);
				}).bindWithEvent(this, [pre.join('/')]))
			);
			text.push(new Element('span', {text: ' / '}));
		}, this);

		text.pop();
		text[text.length-1].addClass('selected').removeEvents('click').addEvent('click', function(e){ e.stop(); });

		this.info.getElement('dd.filemanager-dir').empty().adopt(new Element('span', {text: '/ '}), text);

		if (file.mime=='text/directory') return;

		if (this.Request) this.Request.cancel();

		this.Request = new FileManager.Request({
			url: this.options.url + '?event=detail',
			onSuccess: (function(j){
				var prev = this.preview.removeClass('filemanager-loading').set('html', j && j.content ? j.content.substitute(this.language, /\\?\$\{([^{}]+)\}/g) : '').getElement('img.prev');
				if (prev) prev.addEvent('load', function(){
					this.setStyle('background', 'none');
				});

				var els = this.preview.getElements('button');
				if (els) els.addEvent('click', function(e){
					e.stop();
					window.open(this.get('value'));
				});
			}).bind(this),
			data: {
				directory: this.Directory,
				file: file.name
			}
		}, this).post();
	}
});
