/* class Comments */

function Comments(){
	var self = this;
	
	self.init = function(attr){
		self.attr = attr;
		self.getNodes();
		self.manageForm();
		self.cancel();
		self.submit();
	}
	
	self.getNodes = function(){
		self.reply_links = $('#' + self.attr.container_id + ' a.' + self.attr.reply_links_class);
		self.form = $('#' + self.attr.form_id);
		self.textarea = $('#' + self.attr.textarea_id);
		self.reply_to = $('#' + self.attr.reply_to_id);
		self.btn_cancel = self.form.find('input[@type=reset]');
		self.btn_submit = self.form.find('input[@type=submit]');
	}
	
	self.manageForm = function(){
		self.form.hide();
		self.reply_links.click(function(){
			self.reply_links.show();
			$(this).hide();
			self.form.remove().insertAfter($(this)).show();
			self.reply_to.val($(this).attr('rel'));
			self.textarea.val('');
			self.cancel();
			self.submit();
			return false;
		});
	}
	
	self.cancel = function(){
		self.btn_cancel.click(function(){
			self.reply_links.show();
			self.form.hide();
		});
	}
	
	self.submit = function(){
		self.btn_submit.click(function(){
			var url = self.attr.action_url;
			var text = self.textarea.val();
			
			$.post(url,{
					body: text,
					reply_to: self.reply_to.val()
				},
				function(data){
					location.reload();
				});
			
			return false;
		});
	}
}

$(document).ready(function(){
	var comments = new Comments;
	comments.init({
		container_id: 'comments',
		form_id: 'comment-form',
		action_url: '.',
		textarea_id: 'id_body',
		reply_links_class: 'reply-link',
		reply_to_id: 'id_reply_to'
	});
});
