var ImageChooser = function(config){ this.config = config; }
var photoPath='uploads/hpimages/';
ImageChooser.prototype = {
	lookup : {}, // cache data by image name for easy lookup
	show : function(el, callback){
		if(!this.win){
			this.initTemplates();
			
			this.store = new Ext.data.Store({ url: this.config.url, autoLoad:true,
				reader: new Ext.data.XmlReader({ record:'item' }, ['name', 'fileName','description']),
				listeners: {'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}  }
			});

			var formatSize = function(data){
		        if(data.size < 1024) return data.size + " bytes";
		        else return (Math.round(((data.size*10) / 1024))/10) + " KB";
		    };
			
			var formatData = function(data){
		    	data.shortName = data.name.ellipse(15);
		    	data.sizeString = formatSize(data);
		    	data.dateString = new Date(data.lastmod).format("m/d/Y g:i a");
		    	this.lookup[data.name] = data;
		    	return data;
		    };
			
		    this.view = new Ext.DataView({
				tpl: this.thumbTemplate,
				singleSelect: true,
				overClass:'x-view-over',
				itemSelector: 'div.thumb-wrap',
				emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
				store: this.store,
				listeners: {
					'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
					'dblclick'       : {fn:this.doCallback, scope:this},
					'loadexception'  : {fn:this.onLoadException, scope:this},
					'beforeselect'   : {fn:function(view){return view.store.getRange().length > 0; }}
				},
				prepareData: formatData.createDelegate(this)
			});
		    
			var cfg = { title: 'Photo Browser', id: 'img-chooser-dlg', layout: 'border', width: 800, height: 600,
				modal: true, border: false, buttonAlign:'center',
				items:[
					{ id: 'img-chooser-view', region: 'west', title:'All Photos', split: true, autoScroll:true, collapsible:true, width:125, minWidth:125, maxWidth:225, items: this.view },
					{ id: 'img-detail-panel', region: 'center' }
				],
				buttons: [ { text: 'Close', handler: function(){ this.win.close(); }, scope: this} ],
				keys: { key: 27, handler: function(){ this.win.close(); }, scope: this }
			};
			Ext.apply(cfg, this.config);
			this.win = new Ext.Window(cfg);
		}
		
		this.reset();
		this.win.show(el);
		this.callback = callback;
		this.animateTarget = el;
	},
	
	initTemplates : function(){
		this.thumbTemplate = new Ext.XTemplate(
			'<tpl for=".">',
				'<div class="thumb-wrap" id="{name}">',
				'<div class="thumb"><img src="'+photoPath+'{fileName}" title="{name}"></div>',
				'<span>{name}</span></div>',
			'</tpl>'
		);
		this.thumbTemplate.compile();
		
		this.detailsTemplate = new Ext.XTemplate(
			'<div class="details">',
				'<tpl for=".">',
					'<img src="'+photoPath+'{fileName}">',
					'<div class="description">{description}</div>',
				'</tpl>',
			'</div>'
		);
		this.detailsTemplate.compile();
	},
	
	showDetails : function(){
		var selNode = this.view.getSelectedNodes();
		var detailEl = Ext.getCmp('img-detail-panel').body;
		if (selNode && selNode.length > 0){
			selNode = selNode[0];
			try{Ext.getCmp('ok-btn').enable();}catch(e){}
			var data = this.lookup[selNode.id];
			detailEl.hide();
			this.detailsTemplate.overwrite(detailEl, data);
			detailEl.fadeIn('l', {stopFx:true,duration:.2});
		} else { Ext.getCmp('ok-btn').disable(); detailEl.update(''); }
	},
//	filter : function(){ var filter = Ext.getCmp('filter'); this.view.store.filter('name', filter.getValue()); this.view.select(0); },
	sortImages : function(){ var v = Ext.getCmp('sortSelect').getValue(); this.view.store.sort(v, v == 'name' ? 'asc' : 'desc'); this.view.select(0); },
	reset : function(){ if(this.win.rendered){ Ext.getCmp('filter').reset(); this.view.getEl().dom.scrollTop = 0; } this.view.store.clearFilter(); this.view.select(0); },
	doCallback : function(){
		var selNode = this.view.getSelectedNodes()[0];
		var callback = this.callback;
		var lookup = this.lookup;
		this.win.hide(this.animateTarget, function(){ if(selNode && callback){ var data = lookup[selNode.id]; callback(data); }	});
    },
	
	onLoadException : function(v,o){ this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>'); }
};

String.prototype.ellipse = function(maxLength){ if(this.length > maxLength) return this.substr(0, maxLength-3) + '...'; return this; };
