fairfeed = {
	config: {
		minDuration: 2,
		maxDuration: 15,
		showTimes: true,
		localStorageValidity: 240, // 4 minutes,
		showLinks: true,
		horizontal: true,
		visibleItems: 3,
		serverOffset: 0
	},
	
	debug: {
		expireCache: function() {
			// localStorage['fairfeedpulldate'] = '';
			fairfeed.items.length = 0;
			fairfeed.localStorage.items.save();
		}
	},
	
	items: [],
	addItem: function(id, eventType, date, title, link, image) {
		fairfeed.items.push({'id':id, 'eventType':eventType, 'date':date, 'title':title, 'link':link, 'image':image});
	},

	localStorage: {
		
		_supportsLocalStorage: -1,
		supportsLocalStorage: function() {
			if (fairfeed.localStorage._supportsLocalStorage < 0) {
				try {
					typeof(window.localStorage);
					window.localStorage.length;
					fairfeed.localStorage._supportsLocalStorage = (('localStorage' in window) && window['localStorage'] !== null);
				} catch(e) {
					fairfeed.localStorage._supportsLocalStorage = false;
				} // Catch Security error
			}
			return fairfeed.localStorage._supportsLocalStorage;
		},
		
		items: {
			load: function() {
				if (fairfeed.localStorage.supportsLocalStorage()) {
					if (fairfeed.localStorage.pullDate.isValid()) {
						var storedItemsString = localStorage['fairfeeditems'];
						if (storedItemsString) {
							var storedItems = JSON.parse(JSON.parse(storedItemsString));
							if (storedItems.length < 100) fairfeed.items = storedItems;
						}
					} else {
						localStorage.removeItem('fairfeeditems');
						fairfeed.localStorage.pullDate.reset();
					}
				}
			},
		
			save: function() {
				if (fairfeed.localStorage.supportsLocalStorage()) {
					localStorage.removeItem('fairfeeditems');
					localStorage['fairfeeditems'] = JSON.stringify(fairfeed.items);
				}
			}
		},
		
		pullDate: {
			reset: function() {
				if (fairfeed.localStorage.supportsLocalStorage()) {
					localStorage.removeItem('fairfeedpulldate');
				}
			},
			
			update: function() {
				if (fairfeed.localStorage.supportsLocalStorage()) {
					var now = new Date();
					localStorage['fairfeedpulldate'] = now.toString();
				}
			},
			
			isValid: function() {
				if (fairfeed.localStorage.supportsLocalStorage()) {
					var storedItemsPullDateString = localStorage['fairfeedpulldate'];
					if (storedItemsPullDateString) {
						var storedItemsPullDate = new Date(storedItemsPullDateString);
						var now = new Date();
						if (storedItemsPullDate && Math.floor((now.getTime()-storedItemsPullDate.getTime()) / 1000) < fairfeed.config.localStorageValidity) {
							return true;
						}
					}
				}
				return false;
			}
		},
		
		lastViewed: {
			get: function() {
				if (fairfeed.localStorage.supportsLocalStorage()) {
					var lastViewed = localStorage['fairfeedlastviewed'];
					if (lastViewed) return lastViewed;
				}
				return '';
			},
			
			set: function(id) {
				if (fairfeed.localStorage.supportsLocalStorage()) {
					localStorage['fairfeedlastviewed'] = id;
				}
			}
		}
	},
	
	getFreshEvents: function() {
		var lastViewedEventLocal = fairfeed.localStorage.lastViewed.get();
		
		new Ajax.Request('/events/ajaxLatestEvents/' + lastViewedEventLocal, {
			onComplete: function(transport) {
				if (transport && transport.responseJSON) {
					fairfeed.items.length = 0;

					for (var i=0; i < transport.responseJSON.length; i++) {
						var eventItem = transport.responseJSON[i]['Event'];
						fairfeed.addItem(eventItem['id'], eventItem['event_type_id'], eventItem['timestamp'], eventItem['event'], eventItem['link'], (eventItem['image'].length>0 ? eventItem['image'] : '/img/fairs/hot_icon.gif'));
					};
					
					fairfeed.localStorage.pullDate.update();
					fairfeed.localStorage.items.save();
						
					fairfeed.showNextItem();
				}
			}
		});
	},
	
	showNextItem: function() {
		fairfeed.timer.stop();
		
		var animations = [];
	
		var eventElements = $('ff_clip').select('li');
		
		// WORK OUT HOW MANY TO HIDE & SHOW
		var itemsToShow = 1;
		var itemsToHide = 1;
		
		var animateReveal = true;
		
		if (eventElements.length < fairfeed.config.visibleItems) {
			itemsToHide = 0;

			if (fairfeed.config.horizontal) {
				switch (eventElements.length) {
					case 1:
						itemsToShow = 2;
						break;
					case 2:
						itemsToShow = 1;
						break;
					case 0:
						itemsToShow = 3;
						animateReveal = false;
						break;
				}
			} else {
				switch (eventElements.length) {
					case fairfeed.config.visibleItems:
						itemsToShow = 1;
						break;
					case 0:
						itemsToShow = fairfeed.config.visibleItems;
						animateReveal = false;
						break;
				}
			}
		}
		
		// WORK OF IF WE'VE GOT ENOUGH ITEMS TO SHOW
		if ((fairfeed.localStorage.supportsLocalStorage() && !fairfeed.localStorage.pullDate.isValid()) || itemsToShow >= fairfeed.items.length) {
			
			fairfeed.getFreshEvents();
			
		} else {
		
			if (fairfeed.config.horizontal) {
				for (var i=0; i < itemsToHide; i++) {
					var theElement = eventElements[i];
					animations.push(new Effect.Morph(theElement, {
						sync:true,
						style: { width:'0px' },
						afterFinish: function() {
							Element.remove(theElement);
						}
					}));
					animations.push(new Effect.Fade(theElement, { sync:true }));
				}
			} else {
				for (var i=eventElements.length-1; i >= eventElements.length-itemsToHide; i--) {
					var theElement = eventElements[i];
					animations.push(new Effect.Morph(theElement, {
						sync:true,
						style: { height:'0px' },
						afterFinish: function() {
							Element.remove(theElement);
						}
					}));
					animations.push(new Effect.Fade(theElement, { sync:true }));
				}
			}
		
			var lastId = -1;
		
			for (var s=0; s < itemsToShow; s++) {
				var theItem = fairfeed.items[0];

				if (fairfeed.config.horizontal) {
					if (fairfeed.config.showLinks) {
						Element.insert('ff_clip', {
							bottom: '<li class="event_' + theItem.eventType + '" style="width:' + (animateReveal ? '0' : '255') + 'px;" id="event_li_' + theItem.id + '"><div class="event_pad"><a href="' + theItem.link + '">' + theItem.title + '</a><span>' + (fairfeed.config.showTimes ? fairfeed.relativeTime(theItem.date) : '&nbsp;') + '</span></div></li>'
						});
					} else {
						Element.insert('ff_clip', {
							bottom: '<li class="event_' + theItem.eventType + '" style="width:' + (animateReveal ? '0' : '255') + 'px;" id="event_li_' + theItem.id + '"><div class="event_pad">' + theItem.title + '<span>' + (fairfeed.config.showTimes ? fairfeed.relativeTime(theItem.date) : '&nbsp;') + '</span></div></li>'
						});
					}
				} else {
					Element.insert('ff_clip', {
						top: '<li class="event_' + theItem.eventType + '" style="display:' + (animateReveal ? 'none' : 'block') + ';height:' + (animateReveal ? '0' : '72') + 'px;" id="event_li_' + theItem.id + '"><div class="event_pad"><a href="' + theItem.link + '"><div class="imgdiv"><img src="" alt="' + theItem.image + '" id="vert-feed-' + theItem.id + '" style="display:none;" /></div>' + theItem.title + '</a><span>' + (fairfeed.config.showTimes ? fairfeed.relativeTime(theItem.date) : '&nbsp;') + '</span></div></li>'
					});
					
					var img = $('vert-feed-' + theItem.id);
					img.setOpacity(0);
					img.observe('load', function() {
						new Effect.Appear(this, { duration:0.5 });
					});
					img.src = img.readAttribute('alt');
					img.alt = '';
				}

				if (animateReveal) {
					if (fairfeed.config.horizontal) {
						animations.push(new Effect.Morph('event_li_' + theItem.id, {
							sync:true,
							style: { width:'255px' }
						}));
					} else {
						animations.push(new Effect.Morph('event_li_' + theItem.id, {
							sync:true,
							style: { height:'72px' }
						}));
						
						animations.push(new Effect.Appear('event_li_' + theItem.id, { sync:true }));
					}
				}
			
				lastId = theItem.id;
			
				// Delete the item we have just shown from the in-memory list
				fairfeed.items.splice(0, 1);
				fairfeed.localStorage.items.save();
			
			};
	
			new Effect.Parallel(animations, {
				duration:1.0,
				afterFinish: function() {
					fairfeed.timer.start();
				}
			});
	
			if (lastId >= 0) {
				if (fairfeed.localStorage.supportsLocalStorage()) {
					fairfeed.localStorage.lastViewed.set(lastId);
				} else {
					new Ajax.Request('/events/updateLastViewed/' + lastId);
				}
			}
			
		}
	},
	
	timer: {
		_timer: false,
		randomDuration: function(min, max) {
			return (Math.floor(Math.random()*(fairfeed.config.maxDuration-fairfeed.config.minDuration+1))+fairfeed.config.minDuration) * 1000;
		},
		start: function() {
			fairfeed.timer.stop();
			fairfeed.timer._timer = setTimeout(fairfeed.showNextItem, fairfeed.timer.randomDuration());
		},
		stop: function() {
			clearTimeout(fairfeed.timer._timer);
			fairfeed.timer._timer = false;
		}
	},
	
	relativeTime: function(timestampServer) {
		var nowTimestampClient = Math.floor(new Date().getTime()/1000);
		
		var secondsDifference = nowTimestampClient - (timestampServer - fairfeed.config.serverOffset);
		
		var minuteSeconds = 60;
		var hourSeconds   = minuteSeconds * 60;
		var daySeconds    = hourSeconds * 24;
		
		var finalDifference = false;

		if (secondsDifference > 0) {
			var fullDays     = Math.floor(secondsDifference / daySeconds);
			var fullHours    = Math.floor((secondsDifference - (fullDays*daySeconds)) / hourSeconds);
			var fullMinutes  = Math.floor((secondsDifference - (fullDays*daySeconds) - (fullHours*hourSeconds)) / minuteSeconds);
			
			if (fullMinutes <= 0) {
				var fullSeconds  = Math.floor(secondsDifference - (fullDays*daySeconds) - (fullHours*hourSeconds) - (fullMinutes*minuteSeconds));
				if (fullSeconds > 0) {
					finalDifference = fullSeconds + ' second' + (fullSeconds==1 ? '' : 's') + ' ago';
				}
			} else {
				finalDifference = fullMinutes + ' minute' + (fullMinutes==1 ? '' : 's') + ' ago';
			}
		}
		
		if (finalDifference) {
			return finalDifference;
		} else {
			return 'A few moments ago';
		}
	}
};
