//	if(response.comment){
//		if(response.fk_parent_comment_id) {
//			container = dojo.byId('commentHiderDiv'+response.fk_parent_comment_id);
//			console.log("container:"+container);
//			if($('viewReplyDiv'+response.fk_parent_comment_id)) {
//				$('viewReplyDiv'+response.fk_parent_comment_id).removeClass('hidden');
//			}
//		} else {
//			container = dojo.byId('comment_placeholder');
//		}
//		container.innerHTML += response.comment;
//	}
var _comment = {
	self:this,
	commentId:null,
	fkParentCommentId:null,
	agreeCount:0,
	agreeCountNode:null,
	disagreeCount:0,
	replyCount:0,
	replyCountNode:null,
	disagreeCountNode:null,
	commentNode:null,
	commentHiderNode:null,
	viewReplyNode:null,
	getCommentHiderNode:function() {
		if(!this.commentHiderNode) {
			this.commentHiderNode = $('commentHiderDiv'+this.commentId);
		}
		return this.commentHiderNode;
	},
	incrementReplies:function(){
		this.replyCount++;
		var shower = $E('.commentReplies',this.getCommentNode());
		var hider = $E('.commentRepliesHide',this.getCommentNode());
		$E('a',shower).innerHTML = $E('a',shower).innerHTML.replace(/[0-9]+/,this.replyCount);
		$E('a',hider).innerHTML = $E('a',hider).innerHTML.replace(/[0-9]+/,this.replyCount);
		if(this.getParentComment()) {
			this.getParentComment().incrementReplies();
		}
	},
	getContainer:function() {
		return this.getCommentHiderNode();
	},
	getViewReplyNode:function(){
		if(!this.viewReplyNode) {
			this.viewReplyNode = $('viewReplyDiv'+this.commentId);
		}
		return this.viewReplyNode;
	},
	showViewReplyNode:function(){
		this.getViewReplyNode().removeClass('hidden');
	},
	addComment:function(html) {
		new Element('div').setHTML(html).inject(this.getContainer());
		this.showReplies();
		this.showViewReplyNode();
		this.incrementReplies();
		this.clearReplyField();
		this.hideReplyField();
	},
	getCommentNode:function(){
		if(!this.commentNode) {
			this.commentNode = $('comment'+this.commentId);
		}
		return this.commentNode;
	},
	getAgreeCountNode:function(){
		if(!this.agreeCountNode) {
			this.agreeCountNode = $E('.agreeCount',this.getCommentNode());
		} 
		return this.agreeCountNode;
	},
	getDisagreeCountNode:function(){
		if(!this.disagreeCountNode) {
			this.disagreeCountNode = $E('.disagreeCount',this.getCommentNode());
		} 
		return this.disagreeCountNode;
	},
	showReplyField:function() {
		if (!App.logged_in()) return false;
		dojo.removeClass(dojo.byId(this.commentId+'-reply'), 'hidden');
	},
	clearReplyField:function() {
		$E('.commentField',this.getCommentNode()).value = "";
	},
	hideReplyField:function() {
		dojo.addClass(dojo.byId(this.commentId+'-reply'), 'hidden');
	},
	incrementAgreeCount:function(){
		this.agreeCount++;
		this.getAgreeCountNode().innerHTML = "("+this.agreeCount+")";
	},
	incrementDisagreeCount:function(){
		this.disagreeCount++;
		this.getDisagreeCountNode().innerHTML = "("+this.disagreeCount+")";
	},
	getParentComment:function(){
		if(!this.fkParentCommentId) return false;
		else return commentComponent.getComment(this.fkParentCommentId);
	},
	replies:[],
	isReply:function(){
		return (self.fkParentCommentId) ? 1 : 0; 
	},
	hideReplies:function() {
		var div = $('commentHiderDiv'+this.commentId);
		div.style.display = "none";
		$('thread_reply_hider_'+this.commentId).style.display = "none";
		$('thread_reply_viewer_'+this.commentId).style.display = "";
	},
	showReplies:function(){
		var div = $('commentHiderDiv'+this.commentId);
		div.style.display = "";
		$('thread_reply_hider_'+this.commentId).style.display = "";
		$('thread_reply_viewer_'+this.commentId).style.display = "none";
	},
	toggleReplies:function() {
		var div = $('commentHiderDiv'+this.commentId);
		if(div.style.display != "none")  this.hideReplies();
		else  this.showReplies();
	},
	showLoader:function(type) {
		var div = $('comment_loader_' + type + '_' + this.commentId);
		div.style.display = "block";
	},
	hideLoader:function(type) {
		var div = $('comment_loader_' + type + '_' + this.commentId);
		div.style.display = "none";
	},
	getHeaderNode:function() {
		return $('comment_header_'+this.commentId);	
	},
	highlight:function() {
		var header_node = $('comment_header_'+this.commentId);
		var old_bg = header_node.getStyle('background-color') || '#FFFFFF';
		header_node.setStyle('background-color','#FFFF00');
		setTimeout(function() {
			var color_fade = header_node.effect('background-color', { duration: 2000 }).start('#FFFF00',old_bg);
		},1500);
	},
	getAgreeButtons:function() {
		return [ $E('a.agree',this.getCommentNode()) ];
	},
	getDisagreeButtons:function() {
		return [ $E('a.disagree',this.getCommentNode()) ];
	},
	getToggleButtons:function() {
		var my_els = $ES('a.toggleRepliesButton',this.getCommentNode());
		return (my_els.length) ? my_els.slice(0,2) : [];
	},
	getShowButtons:function() {
		var my_els = $E('a.showReplyButton',this.getCommentNode());
		return (my_els) ? [ my_els ] : [];
	},
	getHideButtons:function() {
		var my_els = $E('a.hideReplyButton',this.getCommentNode());
		return (my_els) ? [ my_els ] : [];
	},
	getSubmitForms:function() {
		var my_els = $E('.ajaxForm',this.getCommentNode());
		return (my_els) ? [ my_els ] : [];	
	}
};
_comment.constructor = function(params) {
	for(var i in params) {
		this[i] = params[i];
	}

};
dojo.provide( 'takkle.view.controls.comment');
dojo.declare( 'takkle.view.controls.comment',null,_comment);

var _page = {};
_page.scroller = new SmoothScroll({ duration: 1500, offset : { x:0,y:-110 }  });
_page.commentHash = {};
_page.commentArray = [];
_page.currentForm = null;
_page.lastPostTime = '';
_page.numPosts = 0;
_page.buttonsEnabled = false;
_page.initComment = function(params){
	
};
//commentComponent.initComment({"agreeCount":0,"commentId":"318652","disagreeCount":0,fkParentCommentId:123});

_page.constructor = function(params){
	this.params = params;
//	if(params["forumId"]) {
//		this.params["commentType"] = 'forumThread';
//		this.params["fkId"] = params["threadId"];
//	} else {
//		if(!params["user"])	throw("Missing required param: user");
//		if(!params["commentType"])	this.params["commentType"] = 'user'; 
//		this.params["fkId"] = USER.id;
//	}
	this.setupEvents();
};
_page.getComment = function(commentId){
	return this.commentHash["comment" + commentId];
};
_page.getCommentNode = function(commentId) {
	return $('comment'+commentId);
};

_page.setCommentEvents = function(cmt) {
	var self = this;

	if (typeof(cmt) != 'object') return;

	cmt.getAgreeButtons().each(function(el) {
		el.removeEvents('click');
		el.addEvent('click', function() { 
			self.vote({ vote: 'agree' , commentId: cmt.commentId  });
		});
	});
	
	cmt.getDisagreeButtons().each(function(el) {
		el.removeEvents('click');
		el.addEvent('click', function() { 
			self.vote({ vote: 'disagree' , commentId: cmt.commentId  });
		});
	});

	cmt.getShowButtons().each(function(el) {
		el.removeEvents('click');
		el.addEvent('click', function() {
			cmt.showReplyField();
		});
	});

	cmt.getHideButtons().each(function(el) {
		el.removeEvents('click');
		el.addEvent('click', function() {
			cmt.hideReplyField();
		});
	});

	cmt.getToggleButtons().each(function(el) {
		el.removeEvents('click');
		el.addEvent('click', function() {
			cmt.toggleReplies();
		});
	});

	cmt.getSubmitForms().each(function(el) {
		el.removeEvents('submit');
		el.onsubmit = function(e) { var ev = new Event(e); ev.stop(); };
		el.addEvent('submit', function(e) {
			var ev = new Event(e);
			ev.stop();
			self.addComment({ form: this});
		});
	});

};

_page.resetEvents = function() {
	for (var comment_obj in this.commentHash) {
		this.setCommentEvents(this.commentHash[comment_obj]);
	}
	this.addUnexistingCommentEvents();
};

_page.initComment = function(params){
	var cmt = new takkle.view.controls.comment(params);
	this.commentHash["comment" + cmt.commentId] = cmt;
	this.setCommentEvents(cmt);

};

_page.gotoComment = function(id) {
	var cmt = this.getComment(id);
	if (!cmt) return false;
	var par_cmt = cmt.getParentComment();
	while (par_cmt) {
		par_cmt.showReplies();
		par_cmt = par_cmt.getParentComment();
	}
	this.scroller.toElement(this.getCommentNode(id));
	
}
	
_page.loadComment = function(id) {
	var cmt = $('comment'+id);
	if(commentComponent.getComment(id))	return false;
	var _commentId = id;
	var _fkParentCommentId = cmt.getProperty('fkParentCommentId');
	var _disagreeCount = cmt.getProperty('disagreeCount');
	var _agreeCount = cmt.getProperty('agreeCount');
	var _replyCount = cmt.getProperty('replyCount');
	commentComponent.initComment({
		commentId:_commentId,
		fkParentCommentId:_fkParentCommentId,
		disagreeCount:_disagreeCount,
		agreeCount:_agreeCount,
		replyCount:_replyCount
	});

}
_page.updateLastPost = function(id) {
	this.lastPostTime = commentComponent.getComment(id).getCommentNode().getProperty('createdDate');
	if (this.params.commentType == 'forumThread') {
		$('threadLastPost').innerHTML = this.lastPostTime; 
		$('threadNumPosts').innerHTML = parseInt($('threadNumPosts').innerHTML) + 1;
	}
};
_page.loadComments = function() {
	$$('.comment').each(function(cmt){
		commentComponent.loadComment(cmt.getProperty('commentId'));
	});
	//this.resetEvents();
	this.addUnexistingCommentEvents();
	var self = this;
	window.addEvent('domready', function() {
		self.enableButtons();
	});
};
_page.addUnexistingCommentEvents = function() {
	var self = this;
	var form = $E('.ajaxForm');
	if (form) {
		form.onsubmit = function(e) { var ev = new Event(e); ev.stop(); };
		
		form.removeEvents('submit');
		form.addEvent('submit', function(e) {
			self.addComment({ form: this });
		});
	}
	this.addPagerEvent();
	
	if (this.params.commentType == 'forumThread') {
		// HJG - the class forumRight was renamed forumAddReply, replaced it here
		var reply_node = $E('.forumAddReply');
		reply_node.addEvent('click', function() {
			self.addReplyLink();
		});
	}
};
_page.addPagerEvent = function() {
	var self = this;
	$$('.more_comments').each(function(el) {
		var comment_page = el.getProperty('next_comment_page') || 2;
		el.removeEvents('click');
		el.addEvent('click', function(e) {
			self.getMoreComments({ page: comment_page });	
		});
	});
};

_page.reloadComments = function(html) {
	$('threadCommentList').innerHTML = html;
	this.commentHash = {};
	this.commentArray = [];
	this.loadComments();
};
_page.toggle_replies =  function(commentId) {
	var cmt = this.getComment(commentId);
	cmt.toggleReplies();
};
_page.showOuterLoader = function(ltype) {
	$('comment_loader_' + ltype + '_').style.display = "block";
};
_page.hideOuterLoader = function(ltype) {
	$('comment_loader_' + ltype + '_').style.display = "none";
};
_page.clearOuterReply = function() {
	if($E('.commentField'))  $E('.commentField').value = "";
};
_page.startComment = function(str) {
	var up_str = str || '';
	var cf = $E('.commentField');
	if (cf) {
		cf.value = up_str;
		cf.focus();
		cf.select();
		this.scroller.toElement(cf);
	}
	return false;
}
_page.addReplyLink = function() {
	if (App.logged_in()) {
		window.location.hash = "commentBottom";
	}
};
_page.sort = function(params) {
	if (this.pageIsBusy()) return false;
	if (!params.type) {
		throw('no sort type passed to sort');
	}

	// form args
	var args;
	if (params.type == 'date') {
		args = { type: 'date' };
	} else if (params.type == 'activity') {
		args = { type: 'activity' };
	} else if (params.type == 'replies') {
		args = { type: 'replies' };
	} else {
		throw('invalid type: ' + params.type);
	}

	this.showLoaderPopup({ message: 'Sorting' });
	// send request
	var self = this;
	server.request({ 
		path: API.getApiPath(this.uriFor('/forum', this.params.forumId, 'thread', this.params.fkId, 'comment', 'sort')),
		onComplete: function(resp) { self.handleResponse(resp) },
		onError: function(resp) { self.handleError(resp) },
		args: args
	});		
}
_page.addComment = function( params ) {
	if (this.pageIsBusy() || !App.logged_in()) return false;

	// validate
	if (!params.form) {
		throw('Must pass form');
	}
	if (params.form.fk_parent_comment_id) {
		this.getComment(params.form.fk_parent_comment_id.value).showLoader('reply');
	} else {
		this.showOuterLoader('reply');
	}
	var self = this;
	this.disableButtons();
	server.request({ 
		path: API.getApiPath(this.uriFor('/comment/add_comment')),
		onComplete: function(resp) {self.handleResponse(resp)},
		onError: function(resp) {self.handleError(resp)},
		args:{fk_id:self.params.fkId,type:self.params.commentType},
		form: params.form
	});		
};
_page.getMoreComments = function(req_obj) {
		if (this.pageIsBusy()) return false;
		this.disableButtons();
		var self = this;
		$E('.more_comments').remove();
		$('seeMoreCommentsLoader').removeClass("hidden");
//		PopupManager.loader_popup("Getting more comments...");
//		API.comment().get_comments(req_obj,{ onComplete: CommentManager.handle_comment });
		server.request({ 
			path: API.getApiPath(this.uriFor('/comment/get_comments')),
			onComplete: function(resp) {self.handleResponse(resp)},
			onError: function(resp) {self.handleError(resp)},
			args:{fk_id:self.params.fkId,type:self.params.commentType,page:req_obj.page}
		});		
};
_page.handleResponse =  function ( response ) {
	if(response.events) {
		for(var i = 0; i < response.events.length; i++) {
			var e = response.events[i];
			var args = e.args || {};
			window.fireEvent(e.name,args);
		}
	} else if (response.fragment && response.success) {
		window.fireEvent('renderFragment',response.fragment);
	} else {
		window.fireEvent('showGenericError',response.message);
	}
	this.enableButtons();
};

_page.handleError = function ( response ) {
		window.fireEvent('showGenericError');
		this.enableButtons();
};

_page.vote = function ( params ) {
	if (this.pageIsBusy() || !App.logged_in()) return false;
	// validate
	if (!params.commentId) {
		throw('Must pass reply id');
	}
	if (!params.vote) {
		throw('Must pass vote to vote');
	}
	if (!(params.vote == 'agree' || params.vote == 'disagree')) {
		throw('Invalid vote value');
	}

	// cast the vote
	var self = this;
	
	params.commentType = (params.commentType) ? params.commentType : this.params.commentType;
	
	commentComponent.getComment(params.commentId).showLoader('vote');
	this.disableButtons();
	server.request({ 
		path: API.getApiPath(this.uriFor('/comment/vote')),
		onComplete: function(resp) { self.handleResponse(resp) },
		onError: function(resp) { self.handleError(resp) },
		args: {
			vote: params.vote,
			comment_id: params.commentId,
			comment_type: params.commentType
		}
	});
};
//Events
_page.setupEvents = function(){
	var _incrementAgreeCount = function(obj) {
		commentComponent.getComment(obj.commentId).incrementAgreeCount();
		commentComponent.getComment(obj.commentId).hideLoader('vote');
	};
	window.addEvent("incrementAgreeCount",_incrementAgreeCount);
	
	var _incrementDisagreeCount = function(obj) {
		commentComponent.getComment(obj.commentId).incrementDisagreeCount();
		commentComponent.getComment(obj.commentId).hideLoader('vote');
	};
	window.addEvent("incrementDisagreeCount",_incrementDisagreeCount);

	var _renderFragment = function(html) {
		commentComponent.reloadComments(html);
		commentComponent.hideLoaderPopup({ message: 'Done' });
	};
	window.addEvent("renderFragment",_renderFragment);

	var _addComment = function(obj) {
		if(obj.fkParentCommentId) {
			commentComponent.getComment(obj.fkParentCommentId).addComment(obj.comment);
			commentComponent.getComment(obj.fkParentCommentId).hideLoader('reply');
		} else {
			//$('comment_placeholder').innerHTML += obj.comment;
			new Element('div').setHTML(obj.comment).injectTop('comment_placeholder');
			commentComponent.hideOuterLoader('reply');
			commentComponent.clearOuterReply();
		}
		if($('noComments'))  $('noComments').style.display = "none";
		commentComponent.loadComment(obj.commentId);
		var comment_obj = commentComponent.getComment(obj.commentId);
		commentComponent.updateLastPost(obj.commentId);
		setTimeout(function() {
			commentComponent.scroller.toElement(comment_obj.getCommentNode());
		},500);
		comment_obj.highlight();
	
		//commentComponent.isAddingComment = false;
	}
	window.addEvent("addComment",_addComment);

	var _showGenericError = function(message) {
		$ES('.genericLoader').each(function(el) {
			el.style.display = "none";
			commentComponent.showErrorPopup({ message: message || 'Error!' });
		});
	};
	window.addEvent("showGenericError",_showGenericError);

	var _showVoteError = function(obj) {
		commentComponent.getComment(obj.commentId).hideLoader('vote');
		commentComponent.showErrorPopup({ message: obj.message || 'Error!' });
	};
	window.addEvent("showVoteError",_showVoteError);

	var _moreCommentsAdded = function(obj) {
		$('seeMoreCommentsLoader').remove();
		new Element('div').setHTML(obj.comment).inject('comment_placeholder');
		//$('comment_placeholder').innerHTML += obj.comment;
		if($('commentField'))	$('commentField').value = "";
		if($('noComments'))  $('noComments').style.display = "none";
		commentComponent.loadComments();
		commentComponent.scroller.toElement(commentComponent.getCommentNode(obj.firstCommentId));
		commentComponent.addPagerEvent();
	};
	window.addEvent("moreCommentsAdded",_moreCommentsAdded);

	var _noMoreComments = function() {
		$('seeMoreCommentsLoader').remove();
		if($('commentField'))	$('commentField').value = "";
		if($('noComments'))  $('noComments').style.display = "none";
	};
	window.addEvent("noMoreComments",_noMoreComments);
};
dojo.provide( 'takkle.view.controls.comments' );
dojo.declare( 'takkle.view.controls.comments', takkle.view.page, _page);
var failedCommentLoads = 0;
var _showSpecificComment = function() {
	try {
		var loc_hash = window.location.hash;
		if (!loc_hash) return;
		var matches = loc_hash.match(/gtc_([0-9|-|a-z]+)/i);
		if (matches) commentComponent.gotoComment(matches[1]);
	} catch(error) {
		if(failedCommentLoads) return false;
		window.addEvent("load",_showSpecificComment);
		failedCommentLoads++;
	}
};
window.addEvent("domready",_showSpecificComment);


