var Live = Class.create();

Live.prototype = {
		
		initialize: function() {
			this.lastEventId = 0;
			this.cityId = 0;
			this.eventStack = [];
			document.observe("dom:loaded", function() {
				setTimeout("live.updateEvents()", 15000);
				new PeriodicalExecuter(live.updateEvents, 60);
				new PeriodicalExecuter(live.renderEvent, 5);
			});
		},
		updateEvents: function() {
			new Ajax.Request(PUBLIC_URL + 'ajax-feed/live-events', {
				parameters: {cityId: live.cityId , page: 10, fromId: live.lastEventId },
				evalJSON: 'force',
				onSuccess: function(transport) {
					if(transport.responseJSON.result == 'success') {
						if( transport.responseJSON.lastEventId > 0 ) {
							live.lastEventId = transport.responseJSON.lastEventId;
						}
						var newEvents = parseInt(transport.responseJSON.newEvents);
						if(newEvents > 0) {
							var responseStack = transport.responseJSON.stack;
							responseStack.each(function(item) {
								live.eventStack.push(item);
							});
						}
					}
				}
			});
		},
		renderEvent: function() {
			var event = live.eventStack.shift();
			if(!event) {
				return false;
			}
			$('newsBox').insert({'top': event});
			var elements = $('newsBox').select('div[data]').toArray();
			var elementCount = elements.size();
			if(elementCount > 0) {
				Effect.Appear(elements[0].previous('p.ui-feed-separator'), { duration: 0.1, queue: 'end' });
				Effect.SlideDown(elements[0], { duration: 1, queue: 'end', transition: Effect.Transitions.linear });
			}
			if(elementCount > 5) {
				for(var i = 5; i < elementCount; i++) {
					elements[i].previous('p.ui-feed-separator');
					elements[i].remove();
				}
			}
		},
		saveCitySettings: function() {
			new Ajax.Request(PUBLIC_URL + 'ajax-feed/save-city-settings', {
				parameters: {cityId: $F('cityId')},
				onSuccess: function(transport) {
					$('citySettingsBox').hide();
					window.location = PUBLIC_URL;
				}
			});
		}
};

var live = new Live();