/*!
 * Ext JS Library 3.1.0
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
var ImageChooser = function(config){
	this.config = config;
}

ImageChooser.prototype = {
    // cache data by image name for easy lookup
    lookup : {},

	show : function(el, fnSelect, fnErase,fnMore){
		if(!this.win){
			this.initTemplates();
			this.fnSelect=fnSelect;
			this.fnErase=fnErase;
			this.fnMore=fnMore;
			this.store = new Ext.data.JsonStore({
			    url: this.config.url,
			    root: 'images',
			    fields: [
			        'id','name','first','url',
			        {name:'size', type: 'float'},
			        {name:'lastmod', type:'date', dateFormat:'timestamp'}

			    ],
			    listeners: {
			    	'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}
			    }
			});
			this.store.load();

			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 se encontraron imágenes</div>',
				store: this.store,
				listeners: {
					'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
					'dblclick'       : {fn:this.doSelect, 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: 'Elige la imagen principal',
		    	id: 'img-chooser-dlg',
		    	layout: 'border',
		    	singleSelect: true,
				minWidth: 500,
				minHeight: 300,
				modal: true,
				closeAction: 'hide',
				border: false,
				items:[{
					id: 'img-chooser-view',
					region: 'center',
					autoScroll: true,
					items: this.view
                   /* tbar:[{
                    	text: 'Filter:'
                    },{
                    	xtype: 'textfield',
                    	id: 'filter',
                    	selectOnFocus: true,
                    	width: 100,
                    	listeners: {
                    		'render': {fn:function(){
						    	Ext.getCmp('filter').getEl().on('keyup', function(){
						    		this.filter();
						    	}, this, {buffer:500});
                    		}, scope:this}
                    	}
                    }, ' ', '-', {
                    	text: 'Ordenar por:'
                    }, {
                    	id: 'sortSelect',
                    	xtype: 'combo',
				        typeAhead: true,
				        triggerAction: 'all',
				        width: 100,
				        editable: false,
				        mode: 'local',
				        displayField: 'name',
				        valueField: 'name',
				        lazyInit: false,
				        value: 'name',
				        store: new Ext.data.ArrayStore({
					        fields: ['name', 'desc'],
					        data : [['name', 'Name'],['size', 'File Size'],['lastmod', 'Last Modified']]
					    }),
					    listeners: {
							'select': {fn:this.sortImages, scope:this}
					    }
				    }]*/
				},{
					id: 'img-detail-panel',
					region: 'east',
					split: true,
					width: 250,
					minWidth: 150,
					maxWidth: 20
				}],
				buttons: [{
					id: 'select-btn',
					text: 'Establecer como principál',
					handler: function(){ this.doSelect();},
					scope: this
				},
				{
					text: 'Borrar',
					id: 'erase-btn',
					handler: function(){
					Ext.MessageBox.show({
				           title: 'Borrar imágen',
				           msg: 'Vas a borrar la imágen seleccionada. Estas seguro?',
				           buttons: Ext.MessageBox.YESNOCANCEL,
				           animEl: 'erase-btn',
				           fn: this.doErase,
				           icon: Ext.MessageBox.QUESTION,
				           scope: this
				       });
					    /*this.doErase(); this.reset();*/ 
					},
					scope: this
				},
				{
					text: 'Subir mas imágenes',
					handler: function(){ this.win.hide(); },
					scope: this
				},
				{
					id: 'accept-btn',
					text: 'Aceptar',
					handler: function(){ this.doMore(); },
					scope: this
				}],
				keys: [{
					key: 27, // Esc key
					handler: function(){ this.win.hide(); },
					scope: this
				},{
					key: 13, // Enter key
					handler: function(){ this.doSelect(); },
					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=".">',
			 '<tpl if="first==\'Principal\'">',
				'<div class="thumb-wrap" id="{name}" style="background-color:#ff9595">',
				'<div class="thumb"><img src="{url}" title="{name}" width></div>',
				'<span>{first}</span></div>',
			 '</tpl>',
			 '<tpl if="first==\'Adiciónal\'">',
				'<div class="thumb-wrap" id="{name}">',
				'<div class="thumb"><img src="{url}" title="{name}"></div>',
				'<!--<span>{first}</span>--></div>',
		     '</tpl>',	
			'</tpl>'
		);
		this.thumbTemplate.compile();

		this.detailsTemplate = new Ext.XTemplate(
			'<div class="details">',
				'<tpl for=".">',
					'<img src="{url}" width="140" height="140"><div class="details-info">',
					'<b>Imagen:</b>',
					'<span>{name}</span>',
					'<b>Fecha de subida:</b>',
					'<span>{lastmod}</span>',
					'<b>Tamaño:</b>',
					'<span>{size}</span>',
					'<b>Tipo:</b>',
					'<span>{first}</span>',
				'</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];
			Ext.getCmp('select-btn').enable();
			Ext.getCmp('erase-btn').enable();
		    var data = this.lookup[selNode.id];
            detailEl.hide();
            this.detailsTemplate.overwrite(detailEl, data);
            detailEl.slideIn('l', {stopFx:true,duration:.2});
		}else{
		    Ext.getCmp('select-btn').disable();
		    Ext.getCmp('erase-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){
			this.view.getEl().dom.scrollTop = 0;
		
		}
		this.view.select(0);
		this.view.store.reload();
		this.view.select(0);
		
	},

	doSelect : function(){
        var selNode = this.view.getSelectedNodes()[0];
		var callback = this.fnSelect;
		var lookup = this.lookup;
		
            if(selNode && callback){
				var data = lookup[selNode.id];
				callback(data);
			}
         
		
    },
    doErase : function(btn){
    	
    	if (btn!='yes') return;
        var selNode = this.view.getSelectedNodes()[0];
		var callback = this.fnErase;
		var lookup = this.lookup;
			
            if(selNode && callback){
				var data = lookup[selNode.id];
				callback(data);
			}
    
    },
	onLoadException : function(v,o){
	    this.view.getEl().update('<div style="padding:10px;">No se han podido cargar los imagenes. Error interno.</div>');
	},
	isFirstSelected: function() {
		var ims=this.view.store.data.items;

		for(i=0;i<ims.length;i++)
		{
		    if(ims[i].data.first=='Principal')
		     return true;
		}
		 return false;
	}
	,
    doMore : function() {
		
		if (!this.isFirstSelected()) {
			Ext.MessageBox.show({
		           title: 'Atención',
		           msg: 'Tienes que elegir la imágen principal para seguir',
		           buttons: Ext.MessageBox.OK,
		           animEl: 'accept-btn',
		           icon: Ext.MessageBox.WARNING
		       });
		 return;	
		}
		else
		{
			this.win.hide();
			this.fnMore();
		}
	}
	
    
};


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