if(!!ajax===false) var ajax=new Array();
var commentObj;

var comments=function() {
	commentObj=this;
	
	this.init=function() {
		if(!!document.getElementById('commentForm')){
			this.f=document.getElementById('commentForm');
			this.t=document.getElementById('commentTable');
		}
		
		this.loader=document.getElementById('loader');
		this.sort=1;
		
		var p=/\/page(\d+)\//i;
		this.pageNum=(p.test(window.location))? RegExp.$1 : 1;
	}
	
	this.submit=function() {
		this.blockFields(true);
		this.showLoader(this.t);
		this.save();
	}
	this._sort=function(sort) {
		this.sort=sort;
		this.refreshList();
	}
	
	this.blockFields=function(bool) {
		this.f.commentSubmit.disabled=bool;
		this.f.comment.readOnly=bool;
	}
	
	this.save=function() {
		var index=ajax.length;
		ajax[index]=new sack();
		ajax[index].getFormValues(this.f);
		ajax[index].requestFile='/comments';
		ajax[index].setVar('do', 'save_comment');
		ajax[index].onCompletion=function() {commentObj.getStatus(index);}
		ajax[index].runAJAX();
	}
	
	this.refreshList=function() {
		var loaderBlock=(!!document.getElementById('nav'))? document.getElementById('nav') : this.t;
		this.showLoader(loaderBlock);
		var index=ajax.length;
		ajax[index]=new sack();
		ajax[index].requestFile='/comments';
		ajax[index].setVar('do', 'get_list');
		ajax[index].setVar('sort', this.sort);
		ajax[index].setVar('type_id', type_id);
		ajax[index].setVar('source_id', source_id);
		ajax[index].setVar('uri', uri);
		ajax[index].setVar('page_num', this.pageNum);
		ajax[index].onCompletion=function() {commentObj.paste(index);}
		ajax[index].runAJAX();
	}
	
	this.nav=function(page) {
		if(/^next$/i.test(page)) this.pageNum++;
		if(/^prev$/i.test(page)) this.pageNum--;
		if(/^(\d+)$/i.test(page)) this.pageNum=page;
		
		this.refreshList();
	}
	
	this.getPos=function(obj) {
		var w=obj.offsetWidth;
		var h=obj.offsetHeight;
		var l=0;
		var t=0;
		
		while(obj) {
			l+=obj.offsetLeft;
			t+=obj.offsetTop;
			obj=obj.offsetParent;
		}
		return {'left':l, 'top':t, 'width': w, 'height':h};
	}
	
	this.showLoader=function(obj) {
		this.loader.style.top=(this.getPos(obj).top+(this.getPos(obj).height/2))+'px';
		this.loader.style.left=(this.getPos(obj).left+(this.getPos(obj).width/2))+'px';
		this.loader.style.display='block';
	}
	
	this.hideLoader=function() {
		this.loader.style.display='none';
	}
	
	this.getStatus=function(index) {
		var response=ajax[index].response.replace(/^\s*|\s*$/g,"");
		this.blockFields(false);
		this.hideLoader();
		
		if(response=='saved') {
			this.f.comment.value='';
			this.refreshList();
		}
		else {
			alert('Не заполнено поле "Комментарий"');
		}
	}
	
	this.paste=function(index) {
		this.hideLoader();
		var comments=document.getElementById('comments');
		comments.innerHTML=ajax[index].response;
		comments.scrollIntoView(true);
	}
}
