Ext.namespace('lor');

lor.CalendarPanel = Ext.extend(Ext.DataView, {
	
	url: null,
	
	itemSelector: 'div.lor-event-entry',
	
	backDaysWindow: null,
	
	nextDaysWindow: null,
	
	futureLimit: 2,
	
	emptyTextTpl: new Ext.XTemplate('<div class="lor-calendar-empty">Nessun evento in calendario per i prossimi giorni</div>'),
	
	initComponent: function()
	{
		var sc = {
			autoDestroy: true,
			autoLoad: true,
			root: 'events',
			idProperty: 'name',
			sortInfo: {
				field: 'date',
				direction: 'ASC'
			},
			fields: [
			{name: 'date', type: 'date', dateFormat: 'Y-m-d'},
			'name',
			'url',
			'location',
			'prov',
			'mapUrl',
			'resultUrl',
			'photoUrl',
			'videoUrl',
			{name: 'cancelled', type: 'boolean'},
			{name: 'valid', type: 'auto'}
			]
		};
		
		if(this.seasonData)
			sc.data = this.seasonData;
		else
			sc.url = this.url;
		
		this.store = new Ext.data.JsonStore(sc);
		this.deferEmptyText = false;
		this.emptyText = this.emptyTextTpl.apply(this);
		
		if(this.backDaysWindow || this.nextDaysWindow)
		{
			this.store.futureEvents = 0;
			this.store.filterBy(function(record){
				if(!this.nextDaysWindow && this.futureLimit > 0 && this.store.futureEvents >= this.futureLimit)
				{
					return false;
				}
				var now = new Date();
				var from = null, to = null;
				if(this.backDaysWindow)
				{
					ms = this.backDaysWindow * 24 * 60 * 60 * 1000;
					from = new Date(now.getTime() - ms);
				}
				if(this.nextDaysWindow)
				{
					ms = this.nextDaysWindow * 24 * 60 * 60 * 1000;
					to = new Date(now.getTime() + ms);
				}
				
				var d = record.get('date');
				if(Ext.isDate(d))
				{
					if(from && d.getTime() < from.getTime())
						return false;
					if(to && d.getTime() > to.getTime())
						return false;
					
					if(d.getTime() > now)
						this.store.futureEvents ++;
				}
				else
					return false;
				
				return true;
			},this);
		}
		
		this.tpl = new Ext.XTemplate(
		'<table class="lor-calendar-table">',
		'<tpl for=".">',
		'<tr class="lor-event-entry">',
		'<td class="lor-calendar-date" style="padding-top: 3px">{[values.date.format("d/m/y")]}</td>',
		'<td class="lor-calendar-text">',
		'<a href="{url}" target="_blank" style="font-weight: bold <tpl if="cancelled">; text-decoration: line-through</tpl>">{name}</a>',
		'<br><tpl if="mapUrl"><a href="{mapUrl}" target="_blank" title="Mappa e indicazioni stradali"></tpl>{location} ({prov})<tpl if="mapUrl"></a></tpl><br>',
		'<tpl if="resultUrl"><a href="{resultUrl}" target="_blank">Classifica</a>&nbsp;</tpl>',
		'<tpl if="photoUrl"><a href="{photoUrl}" target="_blank">Foto</a>&nbsp;</tpl>',
		'<tpl if="videoUrl"><a href="{videoUrl}" target="_blank">Video</a>&nbsp;</tpl>',
		'</td></tr>',
		'</tpl>',
		'</table>',
		{
			compiled: true
		}
		);
		
		lor.CalendarPanel.superclass.initComponent.call(this);
	}
	
});
