var CommentsManager = Class.create({
	initialize:function(pageName, path){
		comments = this;
		this.login_working = false;
		this.idArray = new Array();
		this.lastID = -1;
		this.activeReplyField = -1;
		this.replyIsStub = false;
		this.pageName = pageName;
		this.path = path;
	},
	stub:function(id){
		this.idArray[this.idArray.length] = id;
		document.write("<div id='comments_stub_" + id + "' class=\"commentsStub\">Loading Comments...</div><br/><div id='comments_replyField" + id + "' class='comments_replyField'></div><div id='comments_replies" + id + "' class='comments'></div><br/>");	
	},
	loadComments:function(){
		new Ajax.Request(this.path + '?r=' + Math.random() + '&lastId=' + this.lastID + '&thisPage=' + this.pageName, {
			method: 'get',
			onSuccess: function(xhr){
				//needed to do this because in this function, "this" refers to the window.
				comments.loadCommentResponse(xhr);
			}
		});
	},
	loadCommentResponse:function(xhr){
		var xmlComments = xhr.responseXML.documentElement;
		var messages = xmlComments.getElementsByTagName('message');
		if(messages.length == 0){
			if(this.activeReplyField != -1) this.cancelReply(this.activeReplyField);
			var comments_array = xmlComments.getElementsByTagName('comment');
			for(var i = 0; i < comments_array.length; i++){
				this.createComment(comments_array[i]);
			}
			for(var i = 0; i < this.idArray.length; i++){
				this.setStub(this.idArray[i]);
				this.setStubShowComments(this.idArray[i], false);
				this.setStubPostComment(this.idArray[i], false)
			}
		}
		else{
			this.setReplyDisabled(this.activeReplyField, false);
			var field = messages[0].getAttribute('field');
			var message = messages[0].getAttribute('value');
			$("comments_errorMsg" + this.activeReplyField).innerHTML = message;
			$(field + this.activeReplyField).style.backgroundColor="#FCC";
		}
	},
	createComment:function(comment){
		var id = comment.getAttribute("id");
		// the last ID is remembered to request all newer ones from the server.
		this.lastID = id;
		var parent = $("comments_replies" + comment.getAttribute("parent"));
		if(parent == null){
			return;
		}
		if(parent.className != "comments") parent.className = "comments_replies";
		var newComment = new Element('div', {'class':'comments_comment', id: "comment_" + id});
		var subj = this.gEBTN(comment, 'subject');
		if(subj != null) newComment.appendChild(new Element('span', {'class':"comments_subject"}).update(subj + " - "));;
		var temp = new Element('span', {'class': "comments_author"}).update("By ");
		// hasAttribute was making IE6 barf.
		if(comment.getAttribute("email") != null){
			temp.appendChild(new Element("a", {href:"mailto:" + comment.getAttribute("email")}).update(comment.getAttribute("author")));
		}
		else{
			temp.appendChild(document.createTextNode(comment.getAttribute("author")));
		}
		
		newComment.appendChild(temp);
		newComment.innerHTML += " at ";
		newComment.appendChild(new Element('span', {'class':"comments_date"}).update(comment.getAttribute("date")));
		newComment.appendChild(new Element('br'));
		newComment.appendChild(new Element('span', {'class':"comments_content"}).update(this.gEBTN(comment, 'content')));
		newComment.appendChild(new Element('br'));
		newComment.appendChild(this.setReplyField(id, true));
		newComment.appendChild(new Element('br'));
		newComment.appendChild(new Element('span', {'class':"comments_replies_hidden",id:"comments_replies" + id}));
		parent.appendChild(newComment);
	},
	setStub:function(id){
		$("comments_stub_" + id).update("<a id=\"comment_stubShowComments" + id + "\"></a> - <a id=\"comment_stubPostComment" + id + "\"></a>");
	},
	setStubShowComments:function(id, expanded){
		if(expanded){
			$("comment_stubShowComments" + id).setAttribute("href","javascript:comments.contract('" + id + "')");
			$("comment_stubShowComments" + id).update("Hide Comments");
		}
		else{
			var commentcount = this.countReplies(id);
			$("comment_stubShowComments" + id).setAttribute("href","javascript:comments.expand('" + id + "')");
			$("comment_stubShowComments" + id).update(commentcount + " Comment" + (commentcount==1?"":"s"));
		}
	},
	setStubPostComment:function(id, replying){
		var stubPostComment = $("comment_stubPostComment" + id);
		if(replying){
			stubPostComment.href = "javascript:comments.cancelReply('" + id + "')";
			stubPostComment.innerHTML = "Cancel Comment";
		}
		else{
			stubPostComment.href = "javascript:comments.reply('" + id + "',true)";
			stubPostComment.innerHTML = "Post a Comment";
		}
	},
	setReplyField:function(id, is_stub){
		if(is_stub) return new Element('span', {'class':"comments_replyField", id:"comments_replyField" + id}).update("<A HREF=\"javascript:comments.reply('" + id + "')\" CLASS=\"comments_replyLink\">Reply</A>");
		else {
			this.activeReplyField = id;
			var form = new Element('form',{'class':"comments_replyForm",id:"comments_replyField" + id, name:"comments_replyForm"});
			form.appendChild(new Element('span', {'class':"comments_replyInfo"}).update("Name: <input type=\"text\" maxlength=\"30\" ID=\"comments_replyName" + id + "\"> Email: <input type=\"text\" maxlength=\"40\"  ID=\"comments_replyEmail" + id + "\"> <span class=\"comments_errorMessage\" id=\"comments_errorMsg" + id + "\"></span>"));
			form.appendChild(this.createCancelCommentLink(id));
			form.innerHTML += "<BR><BR>"
					+ "<input type=\"text\" class=\"comments_replySubject\" id=\"comments_replySubject" + id + "\" maxlength=\"80\">"
					+ "<br/>"
					+ "<textarea class=\"comments_replyFieldContent\" id=\"comments_replyContent" + id + "\"></textarea>"
					+ "<input type=\"button\" id=\"comments_button\" onClick=\"javascript:comments.submit('" + id + "')\" value=\"Post Comment\">";
		}
		return form;
	},
	createCancelCommentLink:function(id){
		var ret = "";
		if(this.login_working == true) ret = "<a href=\"javascript:comments.login()\">Login</a> <a href=\"javascript:comments.login()\">Register</a> ";
		ret += "<a href=\"javascript:comments.cancelReply('" + id + "')\">Cancel Comment</a>";
		var temp = new Element('span', {'class':"comments_replyLink",id:"comments_cancelComment" + id}).update(ret);
		return temp;
	},
	expand:function(id){
		var comments_section = $("comments_replies" + id);
		comments_section.style.display = "block";
		this.setStubShowComments(id, true);
	},
	contract:function(id){
		var comments_section = document.getElementById("comments_replies" + id);
		comments_section.style.display = "none";
		this.setStubShowComments(id, false);
	},
	countReplies:function(id){
		var replies = $("comments_replies" + id);
		var total = replies.childNodes.length;
		for(var i = 0; i < replies.childNodes.length; i++){
			total += this.countReplies(this.getNumberFromId(replies.childNodes[i].getAttribute("id")));
		}
		return total;
	},
	getNumberFromId:function(id){
		var ret = "";
		for(var z = 0; z < id.length; z++){
			if(id.charAt(z) >= '0' && id.charAt(z) <= '9') ret += id.charAt(z);
		}
		return ret;
	},
	submit:function(parent_id){
		fields = this.getReplyFields(parent_id);
		var name = encodeURIComponent(fields[0].value);
		var subject = encodeURIComponent(fields[1].value);
		var content = encodeURIComponent(fields[2].value);
		if(fields[3] != null){
			var email = encodeURIComponent(fields[3].value);
		}
		new Ajax.Request(this.path + '?lastId=' + this.lastID + '&thisPage=' + this.pageName, {
			method: 'post',
			parameters:{'type':'guest','name':name,'email':email,'subject':subject,'content':content,'parent_id':parent_id,'thisPage':this.pageName},
			onSuccess: function(xhr){
				comments.loadCommentResponse(xhr);
			}
		});
		this.setReplyDisabled(parent_id, true);
		$("comments_errorMsg" + parent_id).innerHTML = "";
	},
	
	processCommentResponse:function(xhr){
		var xmlComments = xhr.responseXML.documentElement;
		var messages = xmlComments.getElementsByTagName('message');
		if(messages.length == 0){
			this.cancelReply(this.activeReplyField);
			var comments_array = xmlComments.getElementsByTagName('comment');
			for(var i = 0; i < comments_array.length; i++){
				this.createComment(comments_array[i]);
			}
			for(var i = 0; i < this.idArray.length; i++){
				this.setStub(this.idArray[i]);
				this.setStubShowComments(this.idArray[i], false);
				this.setStubPostComment(this.idArray[i], false)
			}
		}
		else{
			this.setReplyDisabled(this.activeReplyField, false);
			var field = messages[0].getAttribute('field');
			var message = messages[0].getAttribute('value');
			$("comments_errorMsg" + this.activeReplyField).innerHTML = message;
			$(field + this.activeReplyField).style.backgroundColor="#FCC";
		}
	},
	reply:function(id, fromStub){
		if(this.activeReplyField != -1) this.cancelReply(this.activeReplyField);
		this.replyIsStub = fromStub;
		if(fromStub){
			this.setStubPostComment(id, true);
		}	
		var repField = $("comments_replyField" + id);
		var parent = repField.parentNode;
		parent.replaceChild(this.setReplyField(id, false), repField);
		this.activeReplyField = id;
	},
	cancelReply:function(id){
		this.activeReplyField = -1;
		var repField = $("comments_replyField" + id);
		if(this.replyIsStub){
			repField.update("");
			this.setStubPostComment(id, false)
		}
		else{
			var parent = repField.parentNode;
			parent.replaceChild(this.setReplyField(id,true), repField);
		}
	},
	setReplyDisabled:function(id, isDisabled){
		var fields = this.getReplyFields(id);
		for(var i = 0; i < fields.length; i++){
			fields[i].style.background = "inherit";
			fields[i].disabled = isDisabled;
		}
	},
	getReplyFields:function(id){
		var a = new Array();
		a[a.length] = $("comments_replyName" + id);
		a[a.length] = $("comments_replySubject" + id);
		a[a.length] = $("comments_replyContent" + id);
		a[a.length] = $("comments_replyEmail" + id);
		a[a.length] = $("comments_button");
		return a;
	},
	gEBTN:function(node, tag){
		if(node.getElementsByTagName(tag).length == 0) return null;
		if(node.getElementsByTagName(tag)[0].firstChild == null) return null;
		return node.getElementsByTagName(tag)[0].firstChild.data;
	}
});