//lc: 01-Sep-09

FR.UI.grid.initGrid = function() {
	this.thumbnailTpl = new Ext.Template('<div class="thumbnailWraper {cls}" style="height:'+(Settings.thumbnail_size+25)+'px;width:'+(Settings.thumbnail_size+20)+'px;">' +
'<div class="thumb" style="	height:'+(Settings.thumbnail_size)+'px;width:'+(Settings.thumbnail_size+10)+'px;">{thumbnail}</div>' +
'<div class="filename"><span ext:qtip="{filename}" unselectable="on">{filename}</span></div></div>');
	FR.UI.grid.thumbnailView = Ext.extend(Ext.grid.GridView, {
	tpl: (Settings.ui_default_view == 'thumbnails') ? FR.UI.grid.thumbnailTpl : null,
	initTemplates : function(){
		FR.UI.grid.thumbnailView.superclass.initTemplates.call(this);
		if(!this.templatedNode){
			this.templatedNode = new Ext.Template('<div class="thumbnailedItem x-unselectable">{content}</div>');
		}
		this.templatedNode.compile();
	},
	onRowSelect : function(row){
		if(this.tpl === null) {
			this.addRowClass(row, "x-grid3-row-selected");
		}
		this.addRowClass(row, "thumbnailedItemSelected");
	},
	onRowDeselect : function(row){
		if(this.tpl === null) {
			this.removeRowClass(row, "x-grid3-row-selected");
		}
		this.removeRowClass(row, "thumbnailedItemSelected");
	},
	prepareData : function(data){
		data.thumbnail = this.getThumbnail(data);
		return data;
	},
	getThumbnail : function(data) {
		var canThumb = false;
		if (data.filetype.indexOf('img') != -1) {
			canThumb = true;
		}
		if (Settings.thumbnails_imagemagick && Settings.thumbnails_imagemagick_ext.indexOf(FR.utils.getFileExtension(data.filename)) != -1) {
			canThumb = true;
		}
		if (canThumb) {
			imgTag = '<img src="'+FR.myfilesBaseURL+'&page=thumbnail&path='+encodeURIComponent(FR.currentPath)+'&filename='+encodeURIComponent(data.filename)+'&filesize='+data.filesize+'&mtime='+data.mtime+'">';
		} else {
			imgTag = '<img src="'+FR.baseURL+'/images/fileman/file_icons/big/'+data.icon+'" width="48" height="48">';
		}
		return '<table border="0" cellpadding="0" cellspacing="0"><tr><td'+(canThumb?' class="lthumb"':'')+'>'+imgTag+'</td></tr></table>';
	},
	doRender : function(cs, rs, ds, startRow, colCount, stripe){
		if(this.tpl === null) {
			return FR.UI.grid.thumbnailView.superclass.doRender.apply(this, arguments);
		}
		// buffers
		var buf = [], rp = {}, r;
		for(var j = 0, len = rs.length; j < len; j++){
			r = rs[j];
			r.data = this.prepareData(r.data);
			rp.content = this.tpl.apply(r.data);
			buf[buf.length] =  this.templatedNode.apply(rp);
		}
		return buf.join("") + '<div style="clear:both"></div>';
	},
	refresh: function(headersToo) {
		if (this.tpl !== null) {
			this.rowSelector = 'div.thumbnailedItem';
		} else {
			this.rowSelector = 'div.x-grid3-row';
		}
		return FR.UI.grid.thumbnailView.superclass.refresh.apply(this, arguments);
	},
	updateAllColumnWidths : function(){
		if (this.tpl === null) {
			return FR.UI.grid.thumbnailView.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.tpl === null) {
			return FR.UI.grid.thumbnailView.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.tpl === null) {
			return FR.UI.grid.thumbnailView.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();
	}});


	this.JsonReaderCols = [
		{name: 'uniqid'},
		{name: 'filename'},
		{name: 'trash_deleted_from'},
		{name: 'share_id'},
		{name: 'filesize', sortType: Ext.data.SortTypes.asInt},
		{name: 'nice_filesize'},
		{name: 'icon'},
		{name: 'type'},
		{name: 'filetype'},
		{name: 'meta_filetype'},
		{name: 'modified', type:'date', dateFormat:'m/d/Y h:i'},
		{name: 'modified2'},
		{name: 'created', type:'date', dateFormat:'m/d/Y h:i'},
		{name: 'mtime'},
		{name: 'hasWebLink'},
		{name: 'comments'},
		{name: 'lockInfo'},
		{name: 'version'}
		];
	this.customColumns.each(function(col) {
		FR.UI.grid.JsonReaderCols.push({name: col.dataIndex});
	});

	//data store
	var ds = new Ext.data.Store({
	    proxy: new Ext.data.HttpProxy({
	        url: this.myfilesBaseURL+'&page=grid'
	    }),
		sortInfo:{field: 'type', direction: 'ASC'},
	    reader: new Ext.data.JsonReader({
	        root: 'files',
	        totalProperty: 'count',
	        id: 'uniqid'
			},
	    	this.JsonReaderCols
		)
	});
	ds.on('load', function(store, records, opts) {
		if (store.reader.jsonData.error) {
			if (FR.currentPath == '/ROOT/HOME') {
				Ext.get('tree').mask();
				Ext.Msg.alert(FR.T('Error'), store.reader.jsonData.error);
			} else {
				Ext.Msg.alert(FR.T('Error'), store.reader.jsonData.error);
				var currentSelectedNode = FR.UI.tree.getSelectionModel().getSelectedNode();
				currentSelectedNode.parentNode.removeChild(currentSelectedNode);
				FR.UI.tree.homeFolderNode.select();
			}
		} else {
			if (store.reader.jsonData.count == 0){
				FR.UI.feedback(FR.T('Folder empty.'));
			}
			FR.UI.grid.onSelectionChange();
			if (FR.UI.grid.highlightOnDisplay) {
				FR.UI.grid.highlight(FR.UI.grid.highlightOnDisplay);
				FR.UI.grid.highlightOnDisplay = false;
			}
		}
	})

	function formatBoolean(value){
        return value ? FR.T('Yes') : FR.T('No');
    };

	this.filenameRendererIconSmall = function (value, p, record) {
		return '<img src="'+FR.baseURL+'/images/fileman/file_icons/small/'+record.data.icon+'" width="16" height="16" align="absmiddle"> '+value;
	}
	
	this.columns = [{
			id: 'filename',
			header: FR.T("Name"),
			dataIndex: 'filename', width:220, hideable: false,
			renderer : this.filenameRendererIconSmall,
			editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: 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, metadata, record, rowIndex, colIndex, store) {
				if (record.data.modified2) {
					//return record.data.modified2;
				}
				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: 'commentsCount',
			header: FR.T("Comments count"),
			dataIndex: 'comments', width:50, hidden:true,
			renderer: function(val) {return val>0?val:'';}
		},{
			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 : '';}
		}];

	this.customColumns.each(function(col) {
		col.custom = true;
		FR.UI.grid.columns.push(col);
	});

	//column model
	var cm = new Ext.grid.ColumnModel(this.columns);
	cm.defaultSortable = true;

	cm.on('hiddenchange', function(cm, colIndex, hideCol) {
		column = cm.getColumnById(cm.getColumnId(colIndex));
		if (column.custom) {
			FR.UI.grid.setMetaCols();
			if (!hideCol) {
				//this is causing problems because of the state restoring
				FR.UI.grid.load(FR.currentPath);
			}
		}
	})

	this.setMetaCols = function() {
		var metadataCols = [];
		cols = cm.getColumnsBy(function(colCfg, indx) {
			col = cm.getColumnById(cm.getColumnId(indx));
			if (col.custom && !col.hidden) {
				metadataCols.push(col.dataIndex);
				return true;
			}
		});
		this.loadParams.metadata = encodeURIComponent(metadataCols.join('|'));
	}
	this.columnModel = cm;

	//grid
	grid = new Ext.grid.EditorGridPanel({
		id: 'FR-Grid-Panel',
		stateId: 'filesGrid',
		stateful: true,
		stateEvents: ['columnresize', 'columnmove', 'sortchange'],
		
		/*
		getState: function() {return{frid:FR.currentPath}},
		applyState: function(state) {console.log(state)},
		*/
		ds: ds,
		cm: cm,
		tbar: FR.UI.gridToolbar.config,
		enableDragDrop: !User.perms.read_only,
		ddGroup : 'TreeDD',
		ddText: FR.T('%1 file(s)').replace('%1', '{0}'),
		stripeRows: false,
		enableColLock:false,
		selModel: new Ext.grid.RowSelectionModel({
			singleSelect:false
		}),
		autoExpandColumn: 'filename',
		loadMask: {msg: FR.T('Loading file list...')},
		view: new FR.UI.grid.thumbnailView({})
	});

	grid.selModel.on('rowselect', function(selModel, rowIndex) {
		FR.currentSelectedFile = FR.UI.grid.panel.getStore().data.items[rowIndex].data;
		if (FR.lastSelectedFile != FR.currentSelectedFile) {
			FR.UI.onSlidePane();
		}
		FR.lastSelectedFile = FR.currentSelectedFile;
	});

	this.editGridFlag = false;
	grid.on('beforeedit', function(e) {
		if (!FR.UI.grid.editGridFlag) {
			e.cancel = true;
		}
	}, this);

	grid.on('rowdblclick', function (grid, rowIndex, e){
		if (Settings.ui_double_click == 'download') {
			FR.actions.downloadSelected();
		} else if (Settings.ui_double_click == 'downloadb') {
			FR.actions.downloadSelected(false, true);
		} else if (Settings.ui_double_click == 'showmenu') {
			FR.UI.grid.onContextMenu();
		} else {
			FR.UI.showPreview();
		}
		e.stopEvent();
		return false;
	});

	grid.on('afteredit', function(edit) {
		FR.actions.renameSelected(edit);
	});
	

	this.panel = grid;
	this.setMetaCols();//to load meta cols stored in state
	
	grid.getView().sortAscText = FR.T(grid.getView().sortAscText);
	grid.getView().sortDescText = FR.T(grid.getView().sortDescText);
	grid.getView().columnsText = FR.T(grid.getView().columnsText);
	
	this.highlight = function(filename) {
		var rowIdx = this.panel.getStore().indexOfId(filename);
		if (rowIdx > -1) {
		    this.panel.getSelectionModel().selectRow(rowIdx);
		}}
	this.load = function(path) {
		ds = this.panel.getStore();
		if (path == '/ROOT/TRASH') {
			ds.proxy.conn.url = FR.baseURL+'/?module=trash&section=ajax&page=grid';
		} else {
			ds.proxy.conn.url = FR.myfilesBaseURL+'&page=grid';
		}
		this.loadParams.path = encodeURIComponent(path);
		ds.load({params: this.loadParams});
		FR.currentPath = path;
		FR.UI.setDNDFolder();
	}
	this.serializeFilenames = function() {
		var s = this.getSelectedFiles();
		var str = '';
		for(var i = 0, len = s.length; i < len; i++){
			var filename = s[i].filename;
			str += '|'+filename;
		}	return str;
	}
	this.getOneSel = function() {
		var selection = this.panel.getSelectionModel().getSelections();
		return selection[0].data;
	}
	this.countSelected = function() {
		selModel = this.panel.getSelectionModel();
		return selModel.getCount();
	}
}

FR.UI.grid.initContextMenu = function() {
	//Grid Context Menu
	cm = new Ext.menu.Menu({
		id: 'grid-contextmenu',
		items: Object.values(FR.UI.grid.actions)
	});
	this.contextMenu.panel = cm;
	this.panel.on('rowcontextmenu', function (grid, rowIndex, e){
		if (FR.UI.grid.countSelected() <= 1) {
			FR.UI.grid.panel.selModel.selectRow(rowIndex);
		}
		if (FR.UI.grid.countSelected() > 0) {
			FR.UI.grid.onContextMenu(grid, rowIndex, e);
		}
		e.stopEvent();
		return false;
	});
	
	this.prepareFileMenu = function() {
		var ga = this.actions;
		if (this.countSel != 0) {
			Object.values(FR.UI.grid.actions).each(function(a) {if (a){a.hide();}});
			Ext.getCmp('grid-contextmenu-quicklink').disable();
			if (FR.currentSection == 'myfiles') {
				ga.metadata.show();
				ga.comment.show();
				if (User.perms.download) {
					if (this.countSel== 1) {
						ga.download.show();
						ga.preview.show();
						if (!Settings.disable_versioning) {
							ga.versioning.show();
						}
					} else {
						ga.download2.show();
					}
				}
				if (!User.perms.read_only) {
					ga.deleteFile.show();
					ga.copy.show();
					if (this.countSel== 1) {
						ga.rename.show();
						ga.zip.show();
						if (this.getOneSel().filetype == 'arch') {
							ga.zip.hide();
							ga.unzip.show();
						}
						//handle custom actions
						var i=0;
						customActions.each(function(ca) {
							i++;
							var action = ga['custom'+i];
							if (!action.settings.extensions) {
								action.show();
							} else {
								if (action.settings.extensions.indexOf(FR.utils.getFileExtension(FR.UI.grid.getOneSel().filename)) != -1) {
									action.show();
									if (action.settings.requiredUserPerms) {
										action.settings.requiredUserPerms.each(function(perm) {
											if (!User.perms[perm]) {
												action.hide();
											}
										});
									}
								}
							}
						});
						//end custom actions
					} else {
						ga.zip.show();
					}
				}
				if (User.perms.email) {
					ga.email.show();
				}
				if (User.perms.weblink) {
					if (this.countSel== 1) {
						Ext.getCmp('grid-contextmenu-quicklink').enable();
						ga.weblink.show();
					}
				}
			} else if (FR.currentSection == 'trash') {
				if (!User.perms.read_only) {
					ga.restore.show();
					ga.deleteFile.show();
				}
			} else {
				if (FR.currentFolderPerms) {
					ga.metadata.show();
					ga.comment.show();
					if (User.perms.download && FR.currentFolderPerms.download) {
						ga.copy.show();
						if (this.countSel== 1) {
							ga.download.show();
							ga.preview.show();
							ga.weblink.show();
							if (!Settings.disable_versioning) {
								ga.versioning.show();
							}
							
							//handle custom actions
							var i=0;
							customActions.each(function(ca) {
								i++;
								var action = ga['custom'+i];
								if (!action.settings.extensions) {
									action.show();
								} else {
									if (action.settings.extensions.indexOf(FR.utils.getFileExtension(FR.UI.grid.getOneSel().filename)) != -1) {
										action.show();
										if (action.settings.requiredUserPerms) {
											action.settings.requiredUserPerms.each(function(perm) {
												if (!User.perms[perm]) {
													action.hide();
												}
											});
										}
									}
								}
							});
							//end custom actions
							
						} else {
							ga.download2.show();
						}
						if (User.perms.email) {
							Ext.getCmp('grid-contextmenu-quicklink').enable();
							ga.email.show();
						}
					}
					if (FR.currentFolderPerms.alter) {
						ga.zip.show();
						if (this.countSel== 1) {
							ga.rename.show();
							if (this.getOneSel().filetype == 'arch') {
								ga.unzip.show();
								ga.zip.hide();
							}
						}
						ga.deleteFile.show();
					}
				}
			}
		}
	}
	
	this.onContextMenu = function() {
		this.prepareFileMenu();
		this.contextMenu.panel.showAt([FR.UI.xy[0]+3, FR.UI.xy[1]+3]);
	}
	
	this.onSelectionChange = function() {
		this.countSel = this.countSelected();
		if (this.countSel== 0) {
			FR.currentSelectedFile = false;
			FR.UI.macCMButton.disable();
		} else {
			FR.UI.macCMButton.enable();
		}
	}
	this.panel.selModel.on('selectionchange', this.onSelectionChange, this);
}