ImageFeed = Class.create({
	initialize: function(element, options){
		Object.extend(this, pH8.Mixin.needsTemplates);
		this.element = $(element);
		this.options = options || {};
		this.hasPrioData = false;
		this.waitForTemplates(this.options.templates,this.onTemplatesLoaded.bind(this));
	},
	delegates: {
		click: {
			'a img, a span': function(e){
				e.stop();
				this.setRawDataIntoSlideshowPlayer(e.element().up('a').identify());
			}
		}
	},
	addEventHandlers: function(){
		this.element.observe('click', Event.delegate(this.delegates.click).bindAsEventListener(this));
	},
	onReady: function(){
		if(this.templatesLoaded){
			this.addEventHandlers();
			this.setRefreshInterval();
			this.getData();
		}
	},
	setRawDataIntoSlideshowPlayer: function(id){
		this.hasPrioData = true;
		this.selected = this.images.get(id);
		document.fire('slideshowplayer:hidedata');
	},
	getData: function(){
		var headers = {};
		
		if(this.images && this.images.size() > 0){
			var today = new Date();
			today.setTime(this.images.get(this.images.keys().first()).timestamp * 1000);
			headers = {
				'If-Modified-Since': today.toUTCString()
			}
		}
		
		this.ajax = new Ajax.Request('/ajax/images.php', {
			method: 'get',
			requestHeaders: headers,
			onSuccess: this.parseJSONData.bind(this)
		});
	},
	parseJSONData: function(transport){
		this.images = $H(transport.responseJSON);
		this.update();
	},
	update: function(){
		var html = this.templates.imagesfeed.process({
			images: this.images.toObject()
		});
		this.element.update(html);
		this.loaded = true;
		document.fire('imagefeed:ready');
		this.element.down('ul').setStyle({
			background: 'none'
		});
	},
	needNewDisplayData: function(){
		if(this.selected){
			this.element.down('ul li a#' + this.selected.id).up('li').removeClassName('active');
		}
		if(!this.hasPrioData){
			if(!this.selected || this.images.size() == 1){
				var randomList = this.images;
			}else{
				var randomList = this.images.clone();
				randomList.unset(this.selected.id);
			}
			var random = Math.floor(Math.random() * (randomList.size()));
			this.selected = randomList.get(randomList.keys()[random]);
		}else{
			this.hasPrioData = false;
		}
		this.animate(this.element.down('ul li a#' + this.selected.id).up('li'));
		
		return this.selected;
	},
	animate: function(el){		
		Effect.Pulsate(el, {
			pulses: 3,
			duration: 1.5,
			afterFinish: function(){
				el.addClassName('active');
			}.bind(this)
		});
	},
	setRefreshInterval: function(){
		this.interval = setInterval(this.getData.bind(this), (this.options.refreshAfterSeconds * 1000));
	},
	onTemplatesLoaded: function(){
		this.templatesLoaded = true;
		this.onReady();
	},
	isLoaded: function(){
		return this.loaded;
	}
});