window.addEvent('domready', function() {	 
	
	var show 	 = 10;
	var msgtotal = $$('#comments li').length;
	var lastmsg	 = $$('#comments li:first-child').getProperty('class');
		lastmsg	 = lastmsg[0];
		
	$$('#commentform input[type=submit]').addEvent('click',function(e){
				
		var name 	= $$('#commentform .name').get('value');
		var message = $$('#commentform .textarea').get('value');
		var hash 	= $$('#commentform .hash').get('value');
		var email 	= $$('#commentform .email').get('value');
		
		var jsonRequest = new Request.JSON({url: "/opening/geouwehoer/add", onComplete: function(data){
	
			showcomments(data);	
	
		}}).get({'name': name[0], 'message': message[0], 'hash': hash[0], 'email': email[0], 'lastmsg': lastmsg});
		
		$$('#commentform .textarea').set('value');

		e.stop();
		
	});
	
	var getcomments  = function(){  
		var jsonRequest = new Request.JSON({url: "/opening/geouwehoer/get", onComplete: function(data){
			showcomments(data);	
		}}).get({'lastmsg': lastmsg});	
	}
	
	getcomments.periodical(10000);
	
	var showcomments = function (data){
					
		if(data){
			data.each(function(item,index){
				var li = new Element('li', { 'html': '<span>'+ item.name +'</span><p>'+ item.message +'</p>', 'opacity': 0 });
				li.inject('comments','top');
				li.fade('in');
				lastmsg = item.time;
			});
			last(show);
		}
			
	}
	
	last(show);
	
	function last(count) {
		 $$('#comments li').setStyle('display','none');
		 $$('#comments li').each(function(item,index){
				if(index < count) { item.setStyle('display','block'); }
		 });
		 if( (msgtotal - show) < 1) {  $('showmore').setStyle('display','none'); } else { $('showmore').setStyle('display','block'); } 
	}
	
	$('showmore').addEvent('click',function(e){ show += 10; last(show); e.stop(); $('showmore').set('html','Lees nog meer reacties'); });
	
});
