var Comment = Class.create({
	
	initialize: function()
	{
		// void
	},
	
	observeComments: function(selector)
	{
		var storeComment = this.storeComment.bind(this);
		var deleteComment = this.deleteComment.bind(this);
		$$(selector).each(function(e)
		{
			// alert('attaching');
			CommentWindow.attach(e, function(e)
			{
				// alert('doing it');
				$$('#add_comment_form').invoke('stopObserving', 'submit');
				$$('#add_comment_form').invoke('observe', 'submit', storeComment);
				
				$$('#comment_list .delete').invoke('stopObserving', 'click');
				$$('#comment_list .delete').invoke('observe', 'click', deleteComment);
			});
		});
	},
	
	deleteComment: function(e)
	{
		Event.stop(e);
		var a = Event.findElement(e, 'a');
		var url = a.href;
		var content = a.up('li');
		if(confirm('Haluatko varmasti poistaa kyseisen kommentin?'))
			new Ajax.Request(url, { method: 'post', onSuccess: function(e) { if(e.responseText == "true") content.remove() } });
	},
	
	storeComment: function(e)
	{
		// alert('attaching');
		Event.stop(e);
		var _this = Event.findElement(e, 'form');
		var deleteComment = this.deleteComment.bind(this);
		_this.request(
			{
				method: 'post',
				onSuccess: function(e) {
					if(e.responseText != "false")
					{
						var content = e.responseText;
						$('comment_list').insert({ 'top' : content});
						$('comment_list').down('li').highlight();
						_this.down('textarea').clear();
						_this.hide();
						$$('#comment_list .delete').invoke('stopObserving', 'click');
						$$('#comment_list .delete').invoke('observe', 'click', deleteComment);
					}
					else
					{ 
						alert('Virhe! Ole hyvä ja yritä uudestaan.');
					}
				}
			}
		);
	}
});

var Qcomment = new Comment();
