var ImageChooser = function(config){
	this.config = config;
}

var images_store = new Ext.data.JsonStore({
    	url: location.href+'&get_images',
    	//autoLoad: true,
    	root: 'images',
    	totalProperty: 'totalCount',
        id:'img_id',
        fields:[
            'mi_id', 'img_id', 'name', 'alt', 'url', 'url_s', 'width',
			{name:'size', type: 'float'},
			{name:'lastmod', type:'date', dateFormat:'timestamp'}
        ]/*,
		
		listeners: { // select the first picture when finish loading the album
	    	'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}
	    }*/
    });
	    
var paging_bar = new Ext.PagingToolbar({
		id: 'paging_bar',
        pageSize: 12,
        store: images_store/*,
        listeners: {
			'select': {fn:function(){ this.view.select(0); }, scope:this, single:true}
	    }*/
    });

ImageChooser.prototype = {
    // cache data by image name for easy lookup
    lookup : {},
    
	init: function() {
		this.detailsTemplate = new Ext.XTemplate(
			'<div class="details">',
				'<img src="{url}" id="large_picture" alt="{alt}" onclick="window.open(\'{url}\',\'{name)\');" />',
				'<br /><span id="photo_name">{name}</span>',
			'</div>'
		);
		this.detailsTemplate.compile();
		
		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.img_id] = data;
			return data;
		};
		
         //trigger the data store load
		images_store.load({params:{start:0, limit:12}});
		images_store.addListener({ // select the first picture when finish loading the album
	    	'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}
	    });
		paging_bar.addListener({
			'select': {fn:function(){ this.view.select(0); }, scope:this, single:true}
	    });
		
	    // Set up images view
	    this.view = new Ext.DataView({
	        id: 'img-chooser-view',	
			singleSelect: true,
			overClass:'x-view-over',
	        itemSelector: 'div.thumb-wrap',
	        style:'overflow:hidden',
	       // multiSelect: false,
	       // plugins: new Ext.DataView.DragSelector({dragSafe:true}),
	        store: images_store,
	        tpl: new Ext.XTemplate(
	            '<tpl for=".">',
	            '<div class="thumb-wrap" id="{img_id}">',
	            '<div class="thumb"><img src="{url_s}" alt="{alt}"></div>',
	            '<!--<span>{shortName}</span>--></div>',
	            '</tpl>'
	        ),
			prepareData: formatData.createDelegate(this),
			listeners: {
				'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
				'beforeselect'   : {fn:function(view){
				        return view.store.getRange().length > 0;
				    }}
			}
	    });

	    this.images = new Ext.Panel({
	        id:'images',
	        region:'center',
	        margins: '5 5 5 0',
	        layout:'fit',
	        autoScroll:false,
	        width: 245,
	        items: this.view,
	        bbar: paging_bar//,
			/*tbar:[{
				text: 'Sort By:'
			}, {
				id: 'sortSelect',
				xtype: 'combo',
				typeAhead: true,
				triggerAction: 'all',
				width: 100,
				editable: false,
				mode: 'local',
				displayField: 'desc',
				valueField: 'name',
				lazyInit: false,
				value: 'name',
				store: new Ext.data.SimpleStore({
					fields: ['name', 'desc'],
					data : [['name', 'Name'],['size', 'File Size'],['lastmod', 'Last Modified']]
				}),
				listeners: {
					'select': {fn:this.sortImages, scope:this}
				}
			}]*/
			
	    });
	    
		this.details = new Ext.Panel({
			id: 'img-detail-panel',
			url: location.href,
			region: 'west',
			split: false,
			width: 405
			//minWidth: 250,
			//maxWidth: 450,
			//autoScroll:true,
		});

	    this.layout = new Ext.Panel({
	    	id: 'img-chooser-dlg',
	        layout: 'border',
	        width:670,
	        height:375,
	        items: [this.images, this.details]
	    });
		
	    this.layout.render('album_layout');
		paging_bar.loading.hideParent = true;
		paging_bar.loading.hide();
	},

	showDetails : function(){
		//debugger;
	    var selNode = this.view.getSelectedNodes();
	    if(selNode[0] == null) // case paging need to select the first photo in the page
	    {
	    	this.view.select(0); //, scope:this, single:true}
	    }	    	
	    var detailEl = Ext.getCmp('img-detail-panel').body;
		if(selNode && selNode.length > 0){
			selNode = selNode[0];
		    var data = this.lookup[selNode.id];
            detailEl.hide();
            this.detailsTemplate.overwrite(detailEl, data);
            detailEl.slideIn('1', {stopFx:true,duration:.2});
            //fix_pic_size();
            //setTimeout('fix_pic_size()',200);
		}else{
		    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);
    }
};

/*******************************************************/
/*******************************************************/
/*******************************************************/

// reference local blank image
Ext.BLANK_IMAGE_URL = '/js/ext-2.2/resources/images/default/s.gif';
 
/*******************************************************/
/*******************************************************/
/*******************************************************/

Ext.onReady(function(){
    Ext.QuickTips.init();

	var album = new ImageChooser();
	album.init();
});

function shortName(name){
    if(name.length > 15){
        return name.substr(0, 12) + '...';
    }
    return name;
};

String.prototype.ellipse = function(maxLength){
    if(this.length > maxLength){
        return this.substr(0, maxLength-3) + '...';
    }
    return this;
};

function fix_pic_size()
{
	picture = document.getElementById("large_picture");
	picture.style.display="none";
	if (picture.width>picture.height)
		picture.style.width = "400px";
	else
		picture.style.height = "340px";
	picture.style.display="";
}