Floco.ext.UploadPanel = Ext.extend(Ext.grid.GridPanel,{
	autoExpandColumn: 'name',
	
	enableColumnResize: false,
	
	enableColumnMove: false,
	
	rec: Ext.data.Record.create([
		{name: 'id'},
 		{name: 'name'},
		{name: 'size'},
		{name: 'type'},
		{name: 'creationdate', type: 'date', dateFormat: 'Y-m-d'},
		{name: 'status'}
	]),
	
	pb: new Ext.ProgressBar({
		text: 'Uploading File'
	}),
	
	initComponent: function(){
		this.store = new Ext.data.Store({
			reader: new Ext.data.JsonReader({
				root: 'bindings',
	        	totalProperty: 'results'
				},[
					{name: 'id'},
			 		{name: 'name'},
					{name: 'size'},
					{name: 'type'},
					{name: 'raw'},
					{name: 'created_on', type: 'date', dateFormat: 'Y-m-d'}
				]
			),
			url: this.gridUrl,
	        autoLoad: false
		});

		this.upBtn = new Floco.ext.UploadButton({
			text: 'Add Files',
			url: this.uploadUrl,
            iconCls: 'upload',
            tooltip: 'Click to add files to this listing.',
            enableWaitMsg: false,
			fTypes: this.fTypes,
			fMsg: this.fMsg
		});
		this.upBtn.on('success', function(btn, res, or){
			this.store.load();
		},this);
		
		this.tbar = [this.upBtn];
		this.bbar = [this.pb];
		
		Floco.ext.UploadPanel.superclass.initComponent.call(this);
		
		this.colModel = new Ext.grid.ColumnModel([
			{id:'name', header: "Filename", dataIndex: 'name'},
			{id:'size', header: "Size", width: 80, dataIndex: 'size', renderer: this.formatBytes },
			{id:'status', header: "Status", width: 80, dataIndex: 'status', renderer: this.formatStatus, hidden:true }
		]);
		
		this.addEvents({
			upload: true
		});
	},
	
	onRender: function(ct, position){
		Floco.ext.UploadPanel.superclass.onRender.apply(this, arguments);

		this.pb.setWidth(this.width-6);
	},
	
	setParams: function(p1,p2) {
		this.store.baseParams = p1;
		this.upBtn.baseParams = p2;
	},
	
	/**
	 * Formats file status
	 * @param {Integer} status
	 * @return {String}
	 */
	formatStatus: function(status){
		switch(status){
			case 0: return("Ready");
			case 1: return("Uploading...");
			case 2: return("Completed");
			case 3: return("Error");
			case 4: return("Cancelled");
		}
	},
	
	/**
	 * Formats raw bytes into kB/mB/GB/TB
	 * @param {Integer} bytes
	 * @return {String}
	 */
	formatBytes: function(bytes){
		if(isNaN(bytes)){return('');}

		var unit, val;

		if(bytes < 999){
			unit = 'B';
			val = (!bytes && this.progressRequestCount >= 1) ? '~' : bytes;
		}else if(bytes < 999999){
			unit = 'kB';
			val = Math.round(bytes/1000);
		}else if(bytes < 999999999){
			unit = 'MB';
			val = Math.round(bytes/100000) / 10;
		}else if(bytes < 999999999999){
			unit = 'GB';
			val = Math.round(bytes/100000000) / 10;
		}else{
			unit = 'TB';
			val = Math.round(bytes/100000000000) / 10;
		}
		return (val + ' ' + unit);
	}
	
});
Ext.reg('uploadpanel', Floco.ext.UploadPanel);