var Blog = Class.create({
	rants: $H({}),
	open_rants: $A(),
	
	initialize: function(){
		setInterval(this.listen.bind(this), 10000);
	},
	
	register_rant: function(id, status){
		if(status != 'open') status='closed';
		this.rants.set(id, $H({
			'id': id,
			'commenter': new Commenter(id),
			'status': status
			})
		);		
	},
	
	get_rant: function(id){
		rant = this.rants.get(id);
		if(!rant) this.notify("No existe el rant "+id);
		return rant;
	},
	
	toggle_comments: function(rant_id, ev){
		Event.stop(ev);
		ev.stop();
		ev.preventDefault();
		rant = this.get_rant(rant_id);
		if(rant.get('status') == 'closed') this.open_comments(rant);
		else this.close_comments(rant);
		Event.stop(ev);
		return false;
	},
	
	open_comments: function(rant){
		rant.set('status', 'open');
		commenter = rant.get('commenter');
		commenter.show_comments().bind(commenter);
	},
	
	close_comments: function(rant){
		rant.set('status', 'closed');
		commenter = rant.get('commenter');
		commenter.hide_comments().bind(commenter);
	},
	
	get_open_rants: function(){
		return this.rants.findAll(
			function(rant){
				return (rant[1].get('status') == 'open');
			}
		);
	},
	
	listen: function(){
		open = this.get_open_rants();
		query = '';
		open.each(
			function(rant){
				query += 'rant[]='+rant[1].get('id')+'&';
			}
		);
		if(query.blank()) return;
		url='/phpajax/socket.php';
		ajax = new Ajax.Request(
			url,
			{
				encoding: 'UTF-8',
				method: 'post',
				parameters: query,
				onSuccess: function(r){this.parse_xml(r).bind(this)}.bind(this)
			}
		);
	},
	
	parse_xml: function(r){
		if(r.responseText == '0') return false;
		Sound.play("/sounds/finished.wav");
		open = this.get_open_rants();
		query = '';
		open.each(
			function(rant){
				rant[1].get('commenter').parse_comments_xml(r, true);
			}
		);
/*
		console.log(open[0][1].get('commenter').rant_id);
		$('textarea_'+open[0][1].get('commenter').rant_id).scrollTo();
*/
		
	},
	
	notify: function(what){
		alert(what);
	}
});