var eventBoxScroller = null;



function getUserEvents( ){
	var eventBox = $("eventBox");
	var firstDiv = eventBox.getFirst();
	var smoothScroll = firstDiv != null;
	var lastEventId = smoothScroll?(firstDiv.get('id').toInt()+1):-1;
	
    ajax = new Request.JSON({
        url: "user-events.json?id="+lastEventId,
        method: 'get',
        onComplete: function(){
        },
        onSuccess: function(userEvents, responseXML) {		
			if (userEvents != null) {
				var eventDiv = null;
				for (var i = 0; i < userEvents.length; i++) {					
					var event = userEvents[i];
					eventDiv = new Element('div', {
							'id': event.id,
							'style': (smoothScroll? 'margin-top: -23px;':'margin-top: 0px;')
						});				
					var date = new Date();
					date.setTime( event.timestamp );
					// add formatted 'time' property to event  
					eventDiv.innerHTML = '<div class="left">'+event.htmlText+'</div><div class="right">'+date.toLocaleTimeString()+'</div>';
					eventBox.grab(eventDiv, 'top');
					if (smoothScroll) eventDiv.tween('margin-top', 0);
				}
				
				var eventDivs = eventBox.getChildren();
				if (eventDivs.length > 20) {
					for (var i = 20; i > eventDivs.length ; i++) {
						eventDivs[i].destroy();
					}
				}
			}
		},
        onCancel: function(){
			
		},
        onFailure: function(){
			
		}
    });
    ajax.send();
}


window.addEvent('domready', function(){
	/*
	if (eventBoxScroller == null) {
		eventBoxScroller = new Fx.Scroll($('eventBox'));
		eventBoxScroller.toTop();
	}*/
	(function(){ getUserEvents(); }).delay(150);
	(function(){ getUserEvents(); }).periodical(12000);
});
  
