Ext.namespace('lor');

lor.Slideshow = Ext.extend(Ext.DataView, {
	
	photoData: null,
	
	itemSelector: '.lor-slideshow-cell',
	
	random: true,
	
	size: 2,
	
	trackOver: true,
	
	autoRefresh: 0,
	
	lastRandom: [],
	
	onPhotoClick: function(dv, index, node)
	{
		var r = this.store.getAt(index);
		var url = r.get('zoomUrl');
		if(!Ext.isEmpty(url))
		{
			var wnd = new Ext.Window({
				width: 800,
				height: 600,
				constrainHeader: true,
				html: {tag: 'img', src: url},
				autoScroll: true,
				title: r.get('title'),
				animateTarget: node
			});
			wnd.show();
		}
	},
	
	initStore: function()
	{
		var photos = this.photoData.photos;
		var storeData = [];

		if(this.random)
		{
			var picked = [];
			
			if(this.size < photos.length)
			{
				var newLast = [];
				while(storeData.length < this.size)
				{
					var index = Math.floor(Math.random() * photos.length);
					
					if(picked.indexOf(index) < 0 && this.lastRandom.indexOf(index) < 0)
					{
						storeData.push(photos[index]);
						picked.push(index);
						newLast.push(index);
					}
				}
				this.lastRandom = newLast;
			}
			else
			{
				storeData = photos.length > this.size ? photos.slice(0,this.size) : photos;
			}
		}
		else
		{
			storeData = photos.length > this.size ? photos.slice(0,this.size) : photos;
		}
		this.store.loadData(storeData, false);
	},
	
	initComponent: function()
	{
		if(!this.photoData)
		{
			this.photoData = {photos: []};
		}
		
		this.store = new Ext.data.JsonStore({
			autoDestroy: true,
			autoLoad: true,
			data: [],
			idProperty: 'url',
			fields: [
			'title',
			'desc',
			'url',
			'zoomUrl',
			{name: 'width', type: 'int', defaultValue: 0}
			]
		});
		
		this.tpl = new Ext.XTemplate(
		'<table class="lor-slideshow-table">',
		'<tpl for=".">',
		'<tr class="lor-slideshow-row">',
		'<td class="lor-slideshow-cell" {[!Ext.isEmpty(values.zoomUrl) ? \'style="cursor: pointer"\' : \'\']}>',
		'<img class="lor-slideshow-photo" src="{url}" ext:qtip="{desc}" <tpl if="values.width &gt; 0"> style="width: {width}px" </tpl>>',
		'<div class="lor-slideshow-title">{title}</div>',
		'</td></tr>',
		'</tpl>',
		'</table>',
		{
			compiled: true
		}
		);
		
		this.on('click',this.onPhotoClick,this);
		this.on('afterrender',function(){
			if(this.autoRefresh > 0)
			{
				Ext.TaskMgr.start({
					run: this.initStore,
					interval: this.autoRefresh,
					scope: this
				});	
			}
			else
			{
				this.initState();
			}
		},this,{scope: this, single: true});
		
		
		lor.Slideshow.superclass.initComponent.call(this);
	}
	
});
