  var ImageChooser = function(config){
	this.config = config;
}

ImageChooser.prototype = {
    lookup : {},
    
	show : function(el){
		if(!this.win){
			this.initTemplates();
			this.store = new Ext.data.JsonStore({
			    url: this.config.url,
			    root: 'images',
			    fields: [
			        'idImg','name','url','descricao','width','height'
					
			    ]
			});
					
			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.idImg] = 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;">Nenhuma Imagem cadastrada.</div>',
				store: this.store,
				loadingText:'<div>Carregando Imagens...</div>',
				listeners: {
					'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
					'click'       : {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: 'Galeria de Imagem',
		    	id: 'img-chooser-dlg',
		    	layout: 'border',
				minWidth: 500,
				minHeight: 300,
				modal: true,
				//closeAction: 'hide',
				border: false,
				listeners:{
					show:function(){this.store.load();},
					scope:this
				},
				items:[{
					id: 'img-chooser-view',
					region: 'center',
					autoScroll: true,
					items: this.view

				}/*,{
					id: 'img-detail-panel',
					region: 'east',
					split: true,
					width: 150,
					minWidth: 150,
					maxWidth: 250
				}*/],
				buttons: [{
				/*	id: 'ok-btn',
					text: 'OK',
					handler: this.doCallback,
					scope: this
				},{*/
					text: 'Fechar',
					handler: function(){ this.win.close(); this.win.destroy(); },
					scope: this			
					}],
				keys: {
					key: 27, // Esc key
					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.animateTarget = el;
	},
	
	initTemplates : function(){
		this.thumbTemplate = new Ext.XTemplate(
			'<tpl for=".">',
				'<div class="thumb-wrap" id="{idImg}" style="float:left;padding:10px;cursor:pointer;">',
				'<div class="thumb"><img src="{url}" title="{name}"></div>',
				'<span>{shortName}</span></div>',				
			'</tpl>'
		);
		this.thumbTemplate.compile();
		
	},
	
	showDetails : function(){
	    var selNode = this.view.getSelectedNodes();
		if(selNode && selNode.length > 0){
			selNode = selNode[0];
		    var data = this.lookup[selNode.id];
		}
	},
	
	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){
			this.view.getEl().dom.scrollTop = 0;
		}
	    this.view.store.clearFilter();
		this.view.select(0);
	},
	
	doCallback : function(){		
			
       		var selNode = this.view.getSelectedNodes()[0];
			var widthAtual = document.body.clientWidth;
			var heightAtual = document.body.clientHeight;
			var obj = document.createElement('img');
			obj.src = selNode.getElementsByTagName('img')[0].src.replace("_A.",".");
			var id = 'img_'+Math.ceil(Math.random(9999999999));
			obj.id = id;
			document.body.appendChild(obj);
			
			if (document.all) {
				obj.onreadystatechange = function() {
					if (obj.readyState == "complete") {
						var largura = parseInt(obj.width)+20;
						var altura =  parseInt(obj.height)+100;
						//alert(altura+'x'+largura+ '\n' + widthAtual+'x'+heightAtual)
						while(largura>widthAtual){
							largura = largura / 2;
						}
						while(altura>heightAtual){	
							altura = altura / 2;
						}
						custom.setWidth(largura);
						custom.setHeight(altura);
						custom.center();
					}
				};
			}else{

				obj.onload = function(){
					var largura = parseInt(obj.width)+10;
					var altura =  parseInt(obj.height)+100;
					while((largura>widthAtual)||(altura>heightAtual)){
						largura = largura / 2	;			
						altura = altura / 2	;						
					}
					custom.setWidth(largura);
					custom.setHeight(altura);
					custom.center();
				}
				
			}
			var largura = parseInt(obj.width)+10;
			var altura =  parseInt(obj.height)+100;
			while((largura>widthAtual)||(altura>heightAtual)){
						largura = largura / 2	;			
						altura = altura / 2	;						
					}
			var custom = new Ext.Window({
				title:'Fit4',
				resizable:true,
				layout: 'border',
				width:largura,
				height:altura,
				items:[{
					  	region: 'center',
						border: false,
					   contentEl: id,
						listeners:{
							/*resize:function(wnd, width, height){
								var objImg = document.getElementById(id);
								objImg.width = width;
								objImg.height = height;
								alert(objImg.width+"x"+objImg.height);
							},*/
							
							
							scope:this
						}
				},{
					region: 'south',
					bodyStyle:'padding:10px;',
					border: false,
					html:'<div style="height:50px;overflow:auto;"><p><b>Nome : </b>'+this.lookup[selNode.id].name+'</p></div>',
					buttons: [{
					id: 'prev-btn',
					text: 'Anterior',					
					disabled : (this.view.getSelectedIndexes() == 0),
					handler: function(){
											this.view.select(parseInt(this.view.getSelectedIndexes())-1);
											custom.close();
											custom.destroy();
											this.doCallback();
									   },
					scope: this
					},{
					id: 'next-btn',	
					text: 'Próximo',
					disabled : (this.view.getSelectedIndexes() == (this.store.getCount()-1)),
					handler: function(){
											this.view.select(parseInt(this.view.getSelectedIndexes())+1);
											custom.close();
											custom.destroy();
											this.doCallback();
									   },
					scope: this
					
					
					}]
				}],
				modal:true
			});
		custom.show();
		
		
		
		
		
    },
	
	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;
};


