
// JavaScript Document

PostNewsCommentManager = Class.create();
						   
PostNewsCommentManager.prototype =	{

	rUrl:null,
	ed:null,
	rAction:null,
	loader:'<img src="/images/loading.gif" />',
	container:null,
	form:null,
	newsid:null,
	commentPager:null,
	
	initialize:function(container, _form, newsid)
	{
		this.container = $(container);
		
		if(this.form = $(_form))
		{
			
			this.rUrl = this.form.action + 'format/json/';
			this.form.observe('submit', this.onFormSubmitClick.bindAsEventListener(this));
		}
			
		this.newsid = newsid;
		this.loadComments(null);	
	},
	
	postComments:function()
	{					
		this.ed = tinyMCE.get('elm1');
		
		var message = this.ed.getContent();
		
		if(!message.blank())
		{

			var params = {newsid: this.newsid, message: message};
		
			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 = '/blogs/getcomments/format/html/' + vari + '&newsid=' + this.newsid;
		else
			var url = '/blogs/getcomments/format/html/?newsid=' + this.newsid;
			
		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));
		}
	}	

};

