var BreakingStories = new Class({
	initialize: function(list_id, timeout) {
		
		this.list = $(list_id);
		this.timeout = timeout;
		this.last_publish_ts = this.list.lang;
		this.allow_load = true;
		
		this.start();
	}
});

BreakingStories.implement({
	
	start: function() {
		
		var obj = this;
		
		obj.list.getParent().setStyle('overflow', 'hidden');
		
		setInterval(function(){
			
			if(obj.allow_load) {
				
				obj.allow_load = false;
				obj.loadNews();
			}
			
		}, obj.timeout);
	},
	
	loadNews: function() {
		
		var obj = this;
		
		new Request.JSON({url: window.location.toString(), onSuccess: function(response){
			
			if(response.data_sz > 0) {
				
				var top = 0;
				obj.updateTime();
				
				for(var i = 0; i < response.data_sz; i++) {
					
					var rec = response.data[i];
					
					var li = new Element('li', {
						html: '<a href="' + rec.href + '">' + rec.title + '</a> <a href="' + rec.href + '" class="view-all">| <span class="min_ago">1</span> min ago</a></li>'
					});
					li.inject(obj.list, 'top');
					var coord = li.getCoordinates();
					top -= coord.height;
					
					obj.list.setStyle('top', top);
				}
				
				new Fx.Morph(obj.list, {
					duration: 500, 
					onComplete: function() {
						
						obj.removeBottomRecords();
						obj.last_publish_ts = response.data[response.data.length - 1].publish_ts;
						obj.allow_load = true;
					}
				}).start({
					top: [top, 0]
				});
			}
			else {
				
				obj.allow_load = true;
			}
			
		}}).get({
			last_publish_ts: obj.last_publish_ts, 
			Event: 'LoadBreakingStories'
		});
	}, 
	
	removeBottomRecords: function() {
		
		var cont_coord = this.list.getParent().getCoordinates();
		this.list.getChildren('li').each(function(li){
			
			var coord = li.getCoordinates();
			if(coord.bottom > cont_coord.bottom) {
				li.dispose();
			}
		});
	}, 
	
	updateTime: function() {
		
		this.list.getChildren('li').each(function(li){
			
			var min = li.getFirst('a.view-all').getFirst('span.min_ago');
			if(min) {
				min.set('text', parseInt(min.get('text')) + 1);
			}
		});
	}
});