
// JavaScript Document

PostCommentManager = Class.create();
						   
PostCommentManager.prototype =	{

	rUrl:null,
	ed:null,
	rAction:null,
	loader:'<img src="/images/loading.gif" />',
	container:null,
	form:null,
	user:null,
	commentPager:null,
	
	initialize:function(container, _form, user)
	{
		this.container = $(container);
		
		if(this.form = $(_form))
		{
			
			this.rUrl = this.form.action + 'format/json/';
			this.form.observe('submit', this.onFormSubmitClick.bindAsEventListener(this));
		}
			
		this.user = user;
		this.loadComments(null);	
	},
	
	postComments:function()
	{	
		this.ed = $('editor1');				
		
		var message = this.ed.value;
		
		if(!message.blank())
		{
			//this.ed.setProgressState(1); 		
			var to = $('to').value;
			var params = {to: to, message: message};//'to='+ to + 'message='+message;
			//var para = 
		
			var options = {
				method : this.form.method,
				parameters : params,
				evalJSON : true,
				onSuccess : this.onPostCommentSuccess.bindAsEventListener(this),
				onFailure : this.onLoadCommentFailure.bindAsEventListener(this)
			};
			
			new Ajax.Request(this.rUrl, options);
		}
		else
		{
			$('form-error').update('A comment is required.');
		}
		
	},
	
	loadComments:function(vari)
	{
		this.setLoading();
		
		if(vari)
			var url = '/user/getcomments/format/html/' + vari + '&user=' + this.user;
		else
			var url = '/user/getcomments/format/html/?user=' + this.user;
			
		var options = {
			method : 'get',
			onSuccess : this.onLoadCommentSuccess.bindAsEventListener(this),
			onFailure : this.onLoadCommentFailure.bindAsEventListener(this)
		};
		
		new Ajax.Request(url, options);
		
	},	
	
	onLoadCommentSuccess:function(transport)
	{
		var result = transport.responseText;
		this.container.update(result);
		this.loadPagingLinks();
		CollapsiblePanel1.close();
		this.ed.value = '';
	},
	
	onPostCommentSuccess:function(transport)
	{
		this.loadComments(null);
		//this.ed.setProgressState(0);
		//alert(transport.responseText);
	},	
	
	onLoadCommentFailure:function(transport)
	{
		var result = transport.responseText;
		alert(result);	
	},

	setLoading:function()
	{
		this.container.update(this.loader);		
	},
	
	onCommentLinkClick:function(e)
    {
        var link = e.element();
		var page = link.search;
		this.loadComments(page);
        Event.stop(e);        
    },
	
	onFormSubmitClick:function(e)
	{
		this.postComments(null);
		Event.stop(e);
	},
	
	loadPagingLinks:function()
	{
		this.commentPager = $('pager');
		if(this.commentPager)
		{
			this.commentPager.select('a').each(function(link) {
				link.observe('click', this.onCommentLinkClick.bindAsEventListener(this));
			}.bind(this));
		}
	}	

};

