var ImageBrowser = {
	
	fileManager : null,
	fmDataView: null,
	uploadForm: null,
	
	createBrowser: function(upload_url, get_data_url){
		
//		upload_url = 'ajax_data.php?cmd=upload_files';
//		get_data_url = 'ajax_data.php?cmd=get_data';
		
		this.createDataview(get_data_url);
    this.uploadForm = new Ext.FormPanel({
      url: upload_url,
			defaultType: 'textfield',
			labelWidth: 100,
			frame: true,
			fileUpload: true,
      enctype:'multipart/form-data',
			title: 'Upload new file',
			items: [
				{xtype: 'textfield', inputType: 'file', fieldLabel: 'Image', name:'main_image', allowBlank: true, anchor: '100%'},
				{xtype: 'button', text: 'Upload', handler: this.uploadFiles, scope: this}
			]
    });
//    this.uploadForm.on('actioncomplete', this._onActionComplete, this);
        
    this.fileManager = new Ext.Window({
			title: 'Browse Image',
      width: 460,
      height: 450,
      closable: true,
      draggable: true,
      plain:true,
      modal: true,
      resizable: false,
      bodyBorder: false,
      border: false,
      items: [
       	new Ext.Panel({
		 			height: 320,
					frame: true,
					autoScroll: true,
					style: 'padding-bottom: 5px; ',					
       		items: [
						this.fmDataView
       		]
       	}),
       	this.uploadForm
      ]
		});		
	},
	
	createDataview: function(get_data_url){
		var tpl = new Ext.XTemplate(
			'<tpl for="." >' +
				'<div style="float: left; width: 100px; height: 100px; padding: 2px; cursor: pointer;" class="thumb">' +
					'<a href="#" onClick="ImageBrowser.changePicture(\'{src}\', {id}); return false;"><img src="{src}" id="img_{id}"/></a>' +
				'</div>' +
			'</tpl>'
		);		
		
		var ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url: get_data_url}),
            reader: new Ext.data.JsonReader(
                {root: 'data', totalProperty: 'total', id: 'id'},
                ['src', 'id']
            ),
            remoteSort: true
		});
		
		this.fmDataView = new Ext.DataView({
      id: 'itemDataView',
      itemSelector:'div.thumb',
			store: ds,
			height: 310,
			width: 417,
      tpl: tpl,
      emptyText: 'No information to display'
    });
	},
	
	show: function(side){
		this.fileManager.show();
		this.fmDataView.store.load();
	},
	close: function(){
		this.fileManager.close();
	},	
	
	_onActionComplete: function(form, action){
		showMessage('Info', action.result.messages);
		this.fmDataView.store.reload()
	},
	
	uploadFiles: function(){
		var form = this.uploadForm.getForm();
		if (form.isValid()){
			form.submit();
		}
	},

	changePicture: function(src, id){
		Ext.getDom(id).src = src;							//???
		var field_id = id + '_hid';							//???
		this.formPanel.getForm().setValues({field_id: id});	//???
		this.fileManager.close();
	}
};