FR.components.gridPanel = Ext.extend(Ext.grid.GridPanel, {
	loadParams: {}, highlightOnDisplay: false,
	initComponent: function() {
		this.initStore();
		this.initColumns();
		this.initContextMenu();
		this.setViewMode();
		Ext.apply(this, {
			region: 'center', border: false,
			stateful: true, stateId: 'filesGrid',
			stateEvents: ['columnresize', 'columnmove', 'sortchange'],
			ddGroup : 'TreeDD', ds: this.store, cm: this.columnModel,
			enableDragDrop: !User.perms.read_only,
			ddText: FR.T('%1 file(s)').replace('%1', '{0}'),
			stripeRows: false, trackMouseOver: true, enableColLock:false,
			selModel: new Ext.grid.RowSelectionModel({
				singleSelect:false,
				listeners: {
					'selectionchange': function(selModel) {
						this.onSelectionChange.delay(150, false, this);
					}, scope: this
				}
			}),
			autoExpandColumn: 'filename',
			loadMask: {msg: FR.T('Loading file list...')},
			view: new FR.components.thumbGridView({
				viewMode: this.viewMode,
				emptyText:
					'<div class="dropIcon x-unselectable"><i class="fa fa-reply fa-rotate-270 fa-5x"></i></div>'+
					'<div style="float:left;" class="x-unselectable">' +
						'<div style="font-size:26px;">'+FR.T('Drop files here')+'</div>'+
						'<div style="font-size:13px;margin-top:10px;">'+FR.T('or use the red "New" button')+'</div>'+
					'</div>',
				rowOverCls: 'tmbItemOver',
				sortAscText: FR.T('Sort Ascending'),
				sortDescText: FR.T('Sort Descending'),
				columnsText: FR.T('Columns')
			}),
			plugins: [new Ext.ux.GridDragSelector({dragSafe:true})],
			listeners: {
				'afterrender': function() {
					this.setMetaCols();
				},
				'rowdblclick': function (grid, rowIndex, e){
					if (FR.currentSection != 'trash') {
						var s = this.store.getAt(rowIndex).data;
						if (!s) {return false;}
						if (FR.currentSection == 'starred' || FR.currentSection == 'search' || FR.currentSection == 'webLinked' ) {
							FR.utils.locateSelected();
						} else {
							var ext = FR.utils.getFileExtension(s.filename);
							if (FR.ext[ext] && FR.UI.gridActions[FR.ext[ext]]) {
								FR.UI.gridActions[FR.ext[ext]].execute();
							} else {
								if (Settings.ui_double_click == 'download') {
									FR.actions.download(FR.currentPath+'/'+s.filename);
								} else if (Settings.ui_double_click == 'downloadb') {
									FR.actions.openFileInBrowser(FR.currentPath+'/'+s.filename);
								} else if (Settings.ui_double_click == 'showmenu') {
									this.showContextMenu();
								} else {
									FR.utils.showPreview();
								}
							}
						}
					}
					e.stopEvent();
					return false;
				},
				'rowmousedown': function(p, rowIndex, e) {
					var trigger = Ext.Element.fly(e.target);
					if (trigger.hasClass('menuTrigger') || trigger.hasClass('triangle')) {
						this.showContextMenu();
					}
				},
				'containermousedown': function(p, e) {
					if (!e.ctrlKey) {
						this.selModel.clearSelections();
						this.countSel = 0;
					}
				},
				'containercontextmenu': function(p, e) {
					this.showContextMenu();
					e.stopEvent();
				},
				'rowcontextmenu': function(grid, rowIndex, e) {
					if (!this.selModel.isSelected(rowIndex)) {
						this.selModel.clearSelections();
						this.selModel.selectRow(rowIndex);
						this.countSel = 1;
						FR.currentSelectedFile = this.store.getAt(rowIndex);
					}
					if (this.countSel > 0) {
						this.showContextMenu();
					}
					e.stopEvent();
				},
				'viewready': function() {

				},
				scope: this
			}
		});
		this.addEvents('folderChange');
		FR.components.gridPanel.superclass.initComponent.apply(this, arguments);
	},
	setViewMode: function() {
		this.viewMode = Settings.ui_default_view;
		var savedViewMode = Ext.state.Manager.getProvider().get('fr-view-mode', false);
		if (savedViewMode) {
			this.viewMode = savedViewMode;
			FR.UI.actions.toggleViewList.setIconClass(((this.viewMode == 'list') ? 'fa fa-th fa-fw' : 'fa fa-list fa-fw'));
		}
	},
	initStore: function() {
		this.JsonReaderCols = [
			{name: 'uniqid', mapping: 'id'},
			{name: 'isFolder', mapping: 'dir'},
			{name: 'filename', mapping: 'n'},
			{name: 'trash_deleted_from', mapping: 'tdf'},
			{name: 'filesize', mapping: 's', sortType: Ext.data.SortTypes.asInt},
			{name: 'nice_filesize', mapping: 'ns'},
			{name: 'icon', mapping: 'i'},
			{name: 'type', mapping: 't'},
			{name: 'thumb', mapping: 'th'},
			{name: 'filetype', mapping: 'ft'},
			{name: 'meta_filetype', mapping: 'mf'},
			{name: 'modified', mapping: 'm', type:'date', dateFormat:'m/d/Y h:i'},
			{name: 'created', mapping: 'c', type:'date', dateFormat:'m/d/Y h:i'},
			{name: 'isNew', mapping: 'new'},
			{name: 'hasWebLink', mapping: 'hW'},
			{name: 'comments', mapping: 'cc'},
			{name: 'label', mapping: 'l'},
			{name: 'star', mapping: 'st'},
			{name: 'path', mapping: 'p'},
			{name: 'lockInfo', mapping: 'lI'},
			{name: 'version', mapping: 'v'}
		];
		Ext.each(FR.UI.grid.customColumns, function(col) {
			this.JsonReaderCols.push({name: col.dataIndex});
		}, this);

		this.store = new FR.components.thumbGridStore({
			proxy: new Ext.data.HttpProxy({url: this.myfilesBaseURL+'&page=grid'}),
			sortInfo: {field: 'filename', direction: 'ASC'},
			reader: new Ext.data.JsonReader({root: 'files', totalProperty: 'count', id: 'id'}, this.JsonReaderCols)
		});
		this.store.on('exception', function(misc) {
			this.body.mask(FR.T('Failed to load file list.<br>Please check your network connection.'));
		}, this);
		this.store.on('beforeload', function(store, records, opts) {
			//store.multiSort([{field:'isFolder', direction:'DESC'}, {field: 'filename', direction: 'DESC'}]);
			store.removeAll(true);
			this.selModel.clearSelections(true);
			this.view.mainBody.update('');
		}, this);
		this.store.on('load', function(store, records, opts) {
			if (this.body.isMasked()) {
				this.body.unmask();
			}
			if (store.reader.jsonData.error) {
				new Ext.ux.prompt({title: FR.T('Error'), text: store.reader.jsonData.error});
				if (FR.currentPath == '/ROOT/HOME') {
					FR.UI.tree.panel.el.mask();
				} else {
					var currentSelectedNode = FR.UI.tree.panel.getSelectionModel().getSelectedNode();
					currentSelectedNode.parentNode.removeChild(currentSelectedNode);
					FR.UI.tree.homeFolderNode.select();
				}
			} else {

				if (store.reader.jsonData.count == 0) {

					//if (Ext.isIE10 || Ext.isIE11 || Ext.isWebKit) {
						var emptyTextEl = this.getView().mainBody.select('div.x-grid-empty').first();
						if (emptyTextEl) {

						}
					//}
				}


				this.fireEvent('folderChange', this, store);
				this.onSelectionChange.delay(0, false, this);
				if (this.highlightOnDisplay) {
					this.highlight(this.highlightOnDisplay);
					this.highlightOnDisplay = false;
				}
				if (store.reader.jsonData.countNewEvents) {
					FR.UI.actions.alerts.updateStatus(parseInt(store.reader.jsonData.countNewEvents));
				}
			}
		}, this);
	},
	initColumns: function() {
		this.columns = [
			{
				id: 'filename',
				header: FR.T("Name"), renderer: function(value, metadata, record) {return record.data.thumbnail;},
				dataIndex: 'filename', width:220, hideable: false
			},{
				id: 'nice_filesize',
				header: FR.T("Size"),
				dataIndex: 'filesize', width: 65,
				renderer: function(value, metadata, record) {return record.data.nice_filesize;}
			},{
				id: 'type',
				header: FR.T("Type"),
				dataIndex: 'type', width: 120
			},{
				custom: true,
				id: 'meta_filetype',
				header: FR.T("Meta Type"),
				dataIndex: 'meta_filetype', width: 120, hidden: true
			},{
				id: 'modified',
				header: FR.T("Date Modified"),
				dataIndex: 'modified', width:120,
				renderer: function(value) {return Ext.util.Format.date(value, FR.T('Date Format: Grid - Modified Date'));}
			},{
				id: 'created',
				header: FR.T("Date Created"),
				dataIndex: 'created', width:120, hidden:true,
				renderer: function(val) {return Ext.util.Format.date(val, FR.T('Date Format: Grid - Modified Date'));}
			},{
				id: 'trash_deleted_from',
				header: FR.T("Deleted from"),
				dataIndex: 'trash_deleted_from',width:180, hidden: true
			},{
				id: 'path',
				header: FR.T("Location"),
				dataIndex: 'path', width:180, hidden: true,
				renderer: FR.utils.humanFilePath
			},{
				id: 'commentsCount',
				header: FR.T("Comments count"),
				dataIndex: 'comments', width:50, hidden:true,
				renderer: function(val) {return val>0?val:'';}
			},{
				id: 'label',
				header: FR.T("Label"),
				dataIndex: 'label', width:50, hidden:true,
				renderer: function(val) {
					if (val) {
						var s = val.split('|');
						return '<span class="FRLabel" style="background-color:'+s[1]+'">'+s[0]+'</span>';
					}
				}
			},{
				id: 'star',
				header: FR.T("Star"),
				dataIndex: 'star', width:50, hidden:true,
				renderer: function(val) {return val ? FR.T('Yes') : '';}
			},{
				id: 'hasWebLink',
				header: FR.T("Web Link"),
				dataIndex: 'hasWebLink', width:50, hidden:true,
				renderer: function(val) {return val ? FR.T('Yes') : '';}
			},{
				id: 'lockInfo',
				header: FR.T("Locked by"),
				dataIndex: 'lockInfo', width:50, hidden:true,
				renderer: function(val) {return val ? val : '';}
			},{
				id: 'version',
				header: FR.T("Version"),
				dataIndex: 'version', width:40, hidden:true,
				renderer: function(val) {return (val && val != '1') ? val : '';}
			},{
				id: 'isNew',
				header: FR.T("Is new"),
				dataIndex: 'isNew', width:40, hidden:true,
				renderer: function(val) {return val ? FR.T('Yes') : '';}
			}
		];

		Ext.each(FR.UI.grid.customColumns, function(col) {
			col.custom = true;
			this.columns.push(col);
		}, this);

		this.columnModel = new Ext.grid.ColumnModel({
			defaults: {sortable: true},
			columns: this.columns
		});

		this.columnModel.on('hiddenchange', function(cm, colIndex, hideCol) {
			var column = cm.getColumnById(cm.getColumnId(colIndex));
			if (column.custom) {
				this.setMetaCols();
				if (!hideCol) {
					//this is causing problems because of the state restoring
					this.load(FR.currentPath);
				}
			}
		}, this);
	},
	setMetaCols: function() {
		var metadataCols = [];
		var cols = this.columnModel.getColumnsBy(function(colCfg, indx) {
			var col = this.columnModel.getColumnById(this.columnModel.getColumnId(indx));
			if (col.custom && !col.hidden) {
				metadataCols.push(col.dataIndex);
				return true;
			}
		}, this);

		this.loadParams.metadata = encodeURIComponent(metadataCols.join('|'));
	},
	getSelectedFiles: function() {
		var s = this.selModel.getSelections();
		var list = [];
		for(var i = 0, len = s.length; i < len; i++){
			var data = s[i].data;
			data.id = s[i].id;
			list.push(data);
		}
		return list;
	},
	getOneSel: function() {
		var selection = this.selModel.getSelections();
		return selection[0];
	},
	countSelected: function() {
		return this.selModel.getCount();
	},
	getByPathAndFilename: function(path, filename) {
		var rowIdx = this.store.findBy(function(record) {
			if (record.data.filename == filename) {
				if (FR.currentPath == path || record.data.path == path) {
					return true;
				}
			}
		});
		return (rowIdx != -1) ? this.store.getAt(rowIdx) : false;
	},
	highlight: function(filename) {
		var rowIdx = this.store.findBy(function(record) {
			if (record.data.filename == filename) {return true;}
		});
		if (rowIdx > -1) {
			this.selModel.selectRow(rowIdx);
			this.getView().focusRow(rowIdx);
		}
	},
	applyUpdates: function(updates) {/* use to apply batch of changes to displayed list of files */
		Ext.each(updates, function(item) {
			var gridItem = FR.UI.gridPanel.getByPathAndFilename(item.path, item.filename);
			if (gridItem) {Ext.apply(gridItem.data, item.data);}
		});
	},
	load: function(path) {
		if (path == '/ROOT/TRASH') {
			this.store.proxy.conn.url = FR.baseURL+'/?module=trash&section=ajax&page=grid';
		} else if (path == '/ROOT/STARRED') {
			this.store.proxy.conn.url = FR.baseURL+'/?module=stars&page=grid';
		} else if (path == '/ROOT/WLINKED') {
			this.store.proxy.conn.url = FR.baseURL+'/?module=weblinks&section=ajax&page=grid';
		} else if (path == '/ROOT/SEARCH') {
			this.store.proxy.conn.url = FR.baseURL+'/?module=search&section=ajax&page=grid';
		} else {
			this.store.proxy.conn.url = FR.myfilesBaseURL+'&page=grid';
		}
		this.loadParams.path = encodeURIComponent(path);
		this.store.load({params: this.loadParams});
		FR.currentPath = path;
	},
	onSelectionChange: new Ext.util.DelayedTask(function(){
		this.countSel = this.countSelected();
		if (this.countSel == 0) {
			FR.currentSelectedFile = false;
		} else  {
			if (this.countSel == 1) {
				FR.currentSelectedFile = this.getOneSel();
			}
		}
		FR.UI.infoPanel.gridSelChange();
		this.showTopMenu();
	}, this),
	showTopMenu: function() {
		var all = ['weblink', 'preview', 'remove', 'more', 'moreSep'];
		Ext.iterate(all, function(k, a) {FR.UI.actions[k].hide();});
		var count=0;
		if (FR.currentSection == 'myfiles') {
			if (this.countSel > 0) {
				if (this.countSel == 1) {
					if (User.perms.download) {
						FR.UI.actions.preview.show();count++;
						if (User.perms.weblink) {
							FR.UI.actions.weblink.show();count++;
						}
					}
				}
				if (!User.perms.read_only) {
					FR.UI.actions.remove.show();count++;
				}
			}
		}
		if (count > 0) {FR.UI.actions.more.show();FR.UI.actions.moreSep.show();}
	},
	initContextMenu: function() {
		this.contextMenu = new Ext.menu.Menu({
			items: FR.UI.grid.arrayActions
		});
	},
	showContextMenu: function() {
		this.prepareFileMenu();
		this.contextMenu.showAt([FR.UI.xy[0]+3, FR.UI.xy[1]+3]);
	},
	prepareFileMenu: function() {
		var ga = FR.UI.gridActions;
		Ext.iterate(ga, function(k, a) {if (a){a.hide();}});
		if (this.countSel == 0) {
			if (FR.utils.currentFolderAllowsUpload()) {
				ga.newItem.show();
				ga.sep5.show();
			}
			ga.refreshExplorer.show();
			var countAll = this.store.getCount();
			if (countAll > 0) {
				ga.selectAllFiles.show();
				if (this.viewMode == 'thumbnails') {
					ga.sortFiles.show();
				}
			}
			return false;
		}
		if (this.countSel == 1) {
			var extension = FR.utils.getFileExtension(FR.currentSelectedFile.data.filename);
			var fileType = FR.currentSelectedFile.data.filetype;
			var isFolder = FR.currentSelectedFile.data.isFolder;
		}
		if (FR.currentSection == 'myfiles') {
			if (this.countSel == 1 && FR.currentSelectedFile.data.star) {
				ga.removeStar.show();
			} else {
				if (User.perms.read_comments && User.perms.write_comments) {
					var showAdd = false;
					Ext.each(FR.UI.gridPanel.getSelectedFiles(), function (item) {
						if (!item.star) {
							showAdd = true;
							return false;
						}
					});
					if (showAdd) {
						ga.addStar.show();
					} else {
						ga.removeStar.show();
					}
				}
			}
			if (User.perms.read_comments && User.perms.write_comments) {
				ga.label.show();
			}
			if (this.countSel == 1) {
				if (User.perms.metadata) {
					ga.metadata.show();
				}
				if (User.perms.read_comments) {
					ga.comment.show();
				}
				if (User.perms.file_history) {
					ga.alog.show();
				}
			}
			if (User.perms.download) {
				ga.download.show();
				ga.sep1.show();
				if (this.countSel == 1) {
					ga.preview.show();
					if (!Settings.disable_versioning) {
						ga.versioning.show();
					}
				}
			}
			if (!User.perms.read_only) {
				ga.sep3.show();
				ga.deleteFile.show();
				ga.copy.show();
				if (this.countSel== 1) {
					ga.rename.show();
					ga.zip.show();
					if (this.getOneSel().data.filetype == 'arch') {
						ga.zip.hide();
						ga.extract.show();
					}
				} else {
					ga.zip.show();
				}
			}
			if (User.perms.email) {
				ga.email.show();
			}
			if (User.perms.weblink && User.perms.download) {
				if (this.countSel== 1) {
					ga.weblink.show();
				}
			}
			//handle custom actions
			var i=0;
			var countDisplayedCA = 0;

			Ext.each(FR.customActions, function(ca) {
				i++;
				var action = ga['custom'+i];
				if (this.countSel == 1 || action.settings.multiple) {
					var show = true;
					//c.a. limited to file types
					if (action.settings.useWith && (action.settings.useWith.indexOf(fileType) == -1)) {show = false;}
					//c.a. limited to extension
					if (action.settings.extensions && action.settings.extensions.indexOf(extension) == -1) {show = false;}
					if (action.settings.requiredUserPerms) {//c.a. limited by permissions
						Ext.each(action.settings.requiredUserPerms, function(perm) {
							if (!User.perms[perm]) {show = false;return false;}
						});
					}
					if (show) {
						action.show();
						countDisplayedCA++;
					}
				}
			}, this);
			if (countDisplayedCA > 0){ga.openWith.show();}
			//end custom actions
		} else if (FR.currentSection == 'trash') {
			if (!User.perms.read_only) {
				ga.restore.show();
				ga.sep3.show();
				ga.deleteFile.show();
			}
		} else if (FR.currentSection == 'starred' || FR.currentSection == 'search' || FR.currentSection == 'webLinked') {
			if (this.countSel == 1) {
				ga.locate.show();
				ga.sep4.show();
			}
			if (User.perms.download) {
				ga.download.show();
				if (this.countSel == 1 && !isFolder) {
					ga.preview.show();
				}
			}
			if (FR.currentSection == 'starred' && !User.perms.read_only) {
				ga.sep1.show();
				ga.removeStar.show();
			}
			if (FR.currentSection == 'webLinked' && User.perms.weblink) {
				if (this.countSel == 1) {
					ga.weblink.show();
				}
				ga.sep3.show();
				ga.unweblink.show();
			}
		} else {
			if (FR.currentFolderPerms) {
				if (User.perms.write_comments && User.perms.read_comments) {
					if (FR.currentFolderPerms.comment) {
						ga.label.show();
					}
					var countStarred = 0;
					Ext.each(FR.UI.gridPanel.getSelectedFiles(), function (item) {
						if (item.star) {
							countStarred++;
						}
					});
					if (countStarred == 0 || (countStarred > 0 && countStarred < this.countSel)) {
						ga.addStar.show();
					} else {
						ga.removeStar.show();
					}
				}

				if (this.countSel == 1) {
					if (User.perms.metadata) {
						ga.metadata.show();
					}
					if (FR.currentFolderPerms.read_comments) {
						if (User.perms.read_comments) {
							ga.comment.show();
						}
					}
				}
				if (User.perms.download && FR.currentFolderPerms.download) {
					if (!User.perms.read_only) {
						ga.copy.show();
					}
					ga.download.show();
					ga.sep1.show();
					if (this.countSel== 1) {
						ga.preview.show();
						if (User.perms.weblink) {
							ga.weblink.show();
						}
						if (!Settings.disable_versioning) {
							ga.versioning.show();
						}
					}
					if (User.perms.email) {
						if (User.perms.weblink) {
						}
						ga.email.show();
					}
				}
				//handle custom actions
				var i=0;
				var countDisplayedCA = 0;
				Ext.each(FR.customActions, function(ca) {
					i++;
					var action = ga['custom'+i];
					if (this.countSel == 1 || action.settings.multiple) {
						var show = true;
						//c.a. limited to file types
						if (action.settings.useWith && (action.settings.useWith != fileType)) {show = false;}
						//c.a. limited to file types
						if (action.settings.extensions && action.settings.extensions.indexOf(extension) == -1) {show = false;}
						if (action.settings.requiredUserPerms) {//c.a. limited by permissions
							Ext.each(action.settings.requiredUserPerms, function(perm) {
								if (!User.perms[perm] || !FR.currentFolderPerms[perm]) {show = false;return false;}
							});
						}
						if (show) {
							action.show();
							countDisplayedCA++;
						}
					}
				}, this);
				if (countDisplayedCA > 0){ga.openWith.show();}
				//end custom actions
				if (FR.currentFolderPerms.alter && !User.perms.read_only) {
					ga.zip.show();
					if (this.countSel== 1) {
						ga.rename.show();
						if (this.getOneSel().data.filetype == 'arch') {
							ga.extract.show();
							ga.zip.hide();
						}
					}
					ga.sep3.show();
					ga.deleteFile.show();
				}
			}
		}
		if (!ga.weblink.isHidden() || !ga.email.isHidden()) {ga.share.show();ga.sep1.show();} else {ga.share.hide();ga.sep1.hide();}
		if (!ga.zip.isHidden() || !ga.extract.isHidden() || !ga.versioning.isHidden() || !ga.alog.isHidden() || !ga.metadata.isHidden()) {ga.more.show();ga.sep2.show();} else {ga.more.hide();ga.sep2.hide();}
	},
	toggleView: function(dontSave) {
		if (this.viewMode == 'list') {
			this.viewMode = 'thumbnails';
		} else {
			this.viewMode = 'list';
		}
		FR.UI.actions.toggleViewList.setIconClass(((this.viewMode == 'list') ? 'fa fa-th fa-fw' : 'fa fa-list fa-fw'));
		var v = this.getView();
		v.viewMode = this.viewMode;
		v.refresh(true);
		if (!dontSave) {
			Ext.state.Manager.getProvider().set('fr-view-mode', this.viewMode);
		}
	},
	onRender: function() {
		FR.components.gridPanel.superclass.onRender.apply(this, arguments);
	}
});




FR.components.thumbGridStore = Ext.extend(Ext.data.Store, {
	sortData : function() {
		this.multiSortInfo = {sorters: [{field:'isFolder', direction: 'DESC'}, {field: this.sortInfo.field, direction: this.sortInfo.direction}], direction: this.sortInfo.direction};
		this.hasMultiSort = true;
		FR.components.thumbGridStore.superclass.sortData.apply(this, arguments);
	}
});




FR.components.thumbGridView = Ext.extend(Ext.grid.GridView, {
	onRowSelect : function(row){
		this.addRowClass(row, (this.viewMode == 'list')?"x-grid3-row-selected":"tmbItemSel");
	},
	onRowDeselect : function(row){
		this.removeRowClass(row, (this.viewMode == 'list')?"x-grid3-row-selected":"tmbItemSel");
	},
	prepareData : function(r) {
		var icons = [];
		if (r.data.isNew) {
			icons.push('<a href="javascript:;" onclick="FR.actions.quickLinks.activityLog('+r.data.uniqid+')"><i class="fa fa-asterisk icon-red" ext:qtip="'+FR.T('This file was created or modified since your last access.')+'"></i></a>');
		}
		if (r.data.hasWebLink) {
			icons.push('<a href="javascript:;" onclick="FR.actions.quickLinks.webLink('+r.data.uniqid+')"><i class="fa fa-link"></i></a>');
		}
		if (User.perms.read_comments && r.data.comments > 0) {
			icons.push('<a href="javascript:;" onclick="FR.actions.quickLinks.comments('+r.data.uniqid+')"><i class="fa fa-comment-o"></i></a>');
		}
		if (r.data.lockInfo) {
			icons.push('<i class="fa fa-lock" ext:qtip="'+FR.T('This file is locked by %1.').replace('%1', r.data.lockInfo)+'"></i>');
		}
		if (r.data.star) {
			icons.push('<i class="fa fa-star-o"></i>');
		}
		var iconsHolder = '<div class="iconsHolder">'+icons.join('')+'</div>';
		var filename = r.data.filename;
		if (!r.data.isFolder) {
			var name = FR.utils.stripFileExtension(r.data.filename);
			var ext = FR.utils.getFileExtension(r.data.filename).toUpperCase();
			var filenameHTML = name +'<span class="ext-list">'+ ext +'</span>';
		} else {
			var filenameHTML = filename;
		}

		if (this.viewMode == 'list') {
			if (r.data.isFolder) {
				var icon = '<i class="fa fa-folder fa-fw fileIcon"></i>';
			} else {
				var icon = '<img src="images/fico/'+r.data.icon+'" class="fileIcon" width="16" height="16" align="absmiddle" />';
			}
			r.data.thumbnail = '<span style="overflow: hidden;">'+icon+ filenameHTML +'</span>' +
				'<div style="position:relative;height:0px;">' +
					'<div style="position:absolute;bottom:1px;right:1px;top:-15px;height:18px;">'+iconsHolder+'</div>' +
				'</div>'
			;
		} else {
			if (r.data.isFolder) {
				return '' +
				'<table cellspacing="0" cellpadding="0" border="0" class="thumbFolder"><tr>' +
					'<td class="thumb"><i class="fa fa-folder fa-lg fa-fw"></i></td>'+
					'<td class="filename"><div class="wrap">' +
						'<span ext:qtip="'+r.data.filename+'" unselectable="on">'+r.data.filename+'</span>'+iconsHolder +
					'</div></td>'+
				'</tr></table>';
			} else {
				if (r.data.label) {
					var s = r.data.label.split('|');
					r.data.labelHTML = '<div style="position:relative"><span class="FRLabel" style="position:absolute;top:5px;left:-5px;background-color:'+s[1]+'">'+s[0]+'</span></div>';
				}
				var thumbSize = Settings.thumbnail_size;
				return '<div class="tmbInner">' +
							(r.data.labelHTML || '') +
							'<div class="center-table"><div class="center-cell">' +
								'<img class="icon" id="itemIcon_'+ r.data.uniqid + r.data.filesize +'" src="images/fico/'+r.data.icon+'" width="'+thumbSize+'" height="'+thumbSize+'" />'+
							'</div></div>' +
						'</div>' +
						'<div class="title" unselectable="on">' +
							'<div class="name" ext:qtip="'+r.data.filename+'<br>'+r.data.nice_filesize+'" style="max-width:'+(Settings.thumbnail_size-44)+'px;">'+filenameHTML+'</div>' +
							iconsHolder +
						'</div>';
			}
		}

	},
	getRows : function() {
		return this.hasRows() ? this.mainBody.query(this.rowSelector) : [];
	},
	doRender : function(cs, rs, ds, startRow, colCount, stripe){
		if (this.viewMode == 'list') {
			Ext.each(rs, function(r) {this.prepareData(r);}, this);
			return FR.components.thumbGridView.superclass.doRender.apply(this, arguments);
		}
		var buf1 = '';
		var buf2 = '';
		Ext.each(rs, function(r) {
			if (r.data.isFolder) {
				buf1 += '<div class="tmbItem typeFolder x-unselectable">'+this.prepareData(r)+'</div>';
			} else {
				buf2 += '<div class="tmbItem x-unselectable">'+this.prepareData(r)+'</div>';
			}
		}, this);
		return buf1 + '<div style="clear:both"></div>' + buf2 + '<div style="clear:both"></div>';
	},
	refresh: function(headersToo) {
		if (this.viewMode == 'thumbnails') {
			this.rowSelector = 'div.tmbItem';
			this.mainHd.setStyle('display', 'none');
		} else {
			this.rowSelector = 'div.x-grid3-row';
			this.mainHd.setStyle('display', 'block');
		}
		FR.components.thumbGridView.superclass.refresh.apply(this, arguments);
		this.loadThumbs();
	},
	updateAllColumnWidths : function(){
		if (this.viewMode == 'list') {
			return FR.components.thumbGridView.superclass.updateAllColumnWidths.apply(this);
		}
		var tw = this.getTotalWidth();
		var clen = this.cm.getColumnCount();
		var ws = [];
		for(var i = 0; i < clen; i++){
			ws[i] = this.getColumnWidth(i);
		}
		this.innerHd.firstChild.firstChild.style.width = tw;
		for(var i = 0; i < clen; i++){
			var hd = this.getHeaderCell(i);
			hd.style.width = ws[i];
		}
		this.onAllColumnWidthsUpdated(ws, tw);
	},
	updateColumnWidth : function(col, width){
		if (this.viewMode == 'list') {
			return FR.components.thumbGridView.superclass.updateColumnWidth.apply(this, arguments);
		}
		var w = this.getColumnWidth(col);
		var tw = this.getTotalWidth();
		this.innerHd.firstChild.firstChild.style.width = tw;
		var hd = this.getHeaderCell(col);
		hd.style.width = w;
		this.onColumnWidthUpdated(col, w, tw);
	},
	updateColumnHidden : function(col, hidden){
		if (this.viewMode == 'list') {
			return FR.components.thumbGridView.superclass.updateColumnHidden.apply(this, arguments);
		}
		var tw = this.getTotalWidth();
		this.innerHd.firstChild.firstChild.style.width = tw;
		var display = hidden ? 'none' : '';
		var hd = this.getHeaderCell(col);
		hd.style.display = display;
		this.onColumnHiddenUpdated(col, hidden, tw);
		delete this.lastViewWidth; // force recalc
		this.layout();
	},
	applyEmptyText : function() {
		var t = this.emptyText;
		if (!FR.utils.currentFolderAllowsUpload() || !FlowUtils.browserSupport.files) {
			if (FR.currentSection == 'starred') {
				this.emptyText = '<div style="font-size:26px;" unselectable="on">'+FR.T('Add stars to files to easily find them later.')+'</div>'
			} else if (FR.currentSection == 'webLinked') {
				this.emptyText = '<div style="font-size:26px;" unselectable="on">'+FR.T('You have not shared any file through web links')+'</div>'
			} else if (FR.currentSection == 'search') {
				this.emptyText = '<div style="font-size:26px;" unselectable="on">'+FR.T('No file was found matching your search criteria')+'</div>'
			} else {
				this.emptyText = '&nbsp;';
			}
		}
		FR.components.thumbGridView.superclass.applyEmptyText.apply(this, arguments);
		this.centerEmptyText();
		this.emptyText = t;
	},
	centerEmptyText: function() {
		var emptyTextEl = this.mainBody.select('div.x-grid-empty').first();
		if (emptyTextEl) {
			var gridWidth = this.grid.getGridEl().getWidth(true);
			var scrollHeight = this.scroller.getHeight(true);
			emptyTextEl.setLeft((gridWidth/2)-160);
			emptyTextEl.setTop((scrollHeight/2)-90);
		}
	},
	layout: function () {
		this.mainBody.setStyle('height', '0px');
		FR.components.thumbGridView.superclass.layout.apply(this);
		var SetSize = function () {
			var h = this.scroller.getHeight();
			var sh = this.scroller.dom.scrollHeight;
			var newBodyH = ((sh > h) ? sh : h);
			newBodyH = newBodyH-10;
			this.mainBody.setStyle('height', newBodyH + 'px');
			this.centerEmptyText();
		};
		SetSize.defer(300, this);
	},
	loadThumbs: function() {
		if (this.viewMode == 'list') {return false;}
		this.ds.each(function(item) {
			if (item.data.thumb) {
				var iconEl = Ext.get('itemIcon_'+item.data.uniqid + item.data.filesize);
				if (iconEl) {
					item.data.thumbImg = Ext.get(Ext.DomHelper.createDom({tag: 'img', cls: 'tmb', alt:''}));
					item.data.thumbImg.on('load', function() {
						if (this.dom) {
							iconEl.replaceWith(this.dom);
							var naturalWidth = this.dom.width;
							var naturalHeight = this.dom.height;
							var largerWidth = (naturalWidth > Settings.thumbnail_size);
							var largerHeight = (naturalHeight > Settings.thumbnail_size);
							var setSize = false;
							if (largerWidth) {
								if (!largerHeight) {
									this.set({width: Settings.thumbnail_size, height: 'auto'});
								} else {
									if (naturalWidth > naturalHeight) {
										this.set({width: Settings.thumbnail_size, height: 'auto'});
									} else {
										this.set({height: Settings.thumbnail_size, width: 'auto'});
									}
								}
							} else {
								if (largerHeight) {
									this.set({height: Settings.thumbnail_size, width: 'auto'});
								}
							}
						}
					});
					item.data.thumbImg.set({src: FR.UI.getThumbURL(item.data)});
				}
			}
		});
	}
});