Sparcq = ( this["Sparcq"] || {}  );


if (!Sparcq.Comments) {
	Sparcq.Comments = function (settings) {
		this.init(settings);
	};
}

Sparcq.Comments.prototype.init = function(args) {
	if (args) {
	}
	this.cloneItem = jQuery('.comments_outer_container .comment_and_replies_default');

	this.comments = {};
	this.nestedComments = {};
	this.commentList = [];
	this.listType = args.comment_type;
	this.objectId = args.id;
	this.totalComments = 0;
	this.replyCounts = {};
	this.defaultUserIcon = '/images/layout/placeholders/userProfilePic_25x25.png';
	this.numPerPage = 10;
	this.firstLoad = true;
	
	switch(this.listType) {
		case 'topic':
			//this.loadTopicComments(this.objectId);
			var self = this;
			this.new_paginator = new Sparcq.Paginator({
				pageContainer: jQuery('.comments_outer_container'),
				paginatorContainer: jQuery('.comment_paginator_holder'),
				numPerPage: this.numPerPage,
				callback: function(page_num) {
					self.loadTopicComments(page_num);
				}
			});
		break;
		case 'user':
			var self = this;
			this.new_paginator = new Sparcq.Paginator({
				pageContainer: jQuery('.comments_outer_container'),
				paginatorContainer: jQuery('.comment_paginator_holder'),
				numPerPage: this.numPerPage,
				callback: function(page_num) {
					self.loadUserComments(page_num);
				}
			});

			//this.loadUserComments(this.objectId);
		break;
	}
	
	
};

Sparcq.Comments.prototype.loadTopicComments = function(page,success_callback) {
	var self = this;
	page = page || 1;

	SPARCQ.API.callMethod('topic.getComments', {
		params: {
			entry_id: this.objectId,
			return_count: 10,
			page: page
		},
		onSuccess: function(ret) {
			self.handleTopicCommentsLoad(ret);
			if (success_callback) {
				success_callback.call(self);
			}
		},
		onError: function(ret,id) {
			alert('error comment list for ' + id);
		}
	});

};

Sparcq.Comments.prototype.loadUserComments = function(page) {
	var self = this;
	page = page || 1;
	
	SPARCQ.API.callMethod('user.getComments', {
		params: {
			sparcq_member_id: this.objectId,
			return_count: 10,
			page: page
		},
		onSuccess: function(ret) {
			self.handleUserCommentsLoad(ret);
		},
		onError: function(ret,id) {
			alert('error comment list for ' + id);
		}
	});
	
};

Sparcq.Comments.prototype.handleUserCommentsLoad = function(ret) {
	
	ret = ret.parsed_return;

	var new_page = ret.page;
	this.new_paginator.setTotalPages(ret.total_pages);
	this.new_paginator.createCachedPage(ret,new_page);

	if (this.firstLoad) {
		var comment_total_holder = jQuery('#ratings_comments_holder');
		var template_html = comment_total_holder.html();
		
		this.totalComments = ret.comment_count;
		
		comment_total_holder.html(Sparcq.SQ.parseHtml(
			template_html,{
				total_comments: '0 comments'	
			}));
		comment_total_holder.show();
		jQuery('#ratings_comments_box').show();
		
		jQuery('#ratings_comments_link').click(function() {
			jQuery('#ratings_comments_box').trigger('load', 'comments');
		});
	}

	this.addComments(ret.comments,new_page);
	
	if (this.firstLoad) {
		this.updateCommentTotal();	
		this.checkForAnchorScroll();
	}

	this.firstLoad = false;

};

Sparcq.Comments.prototype.handleTopicCommentsLoad = function(ret) {

	ret = ret.parsed_return;

	var new_page = ret.page;
	this.new_paginator.setTotalPages(ret.total_pages);
	this.new_paginator.createCachedPage(ret,new_page);

	if (this.firstLoad) {

		var comment_total_holder = jQuery('#ratings_comments_holder');
		var template_html = comment_total_holder.html();
		
		this.totalComments = ret.comment_count;

		comment_total_holder.html(Sparcq.SQ.parseHtml(
			template_html,{
				total_comments: '0 comments'	
			}));
		

		comment_total_holder.show();
		jQuery('#ratings_comments_box').show();
		
		jQuery('#ratings_comments_link').click(function() {
			jQuery('#ratings_comments_box').trigger('load');
		});
	}
	
	this.addComments(ret.comments,new_page);
	
	if (this.firstLoad) {
		this.updateCommentTotal();
		this.checkForAnchorScroll();
	}
	this.firstLoad = false;
};

Sparcq.Comments.prototype.addCommentFromApi = function(cmt,page_num,skip_total) {
	if (!skip_total) {
		this.totalComments++;
	}
	if (cmt.parent_comment_id) {
		this.replyCounts[cmt.parent_comment_id] = (this.replyCounts[cmt.parent_comment_id]) ? this.replyCounts[cmt.parent_comment_id] + 1 : 1;
	}
	this.addComment({
		parent_comment_id: cmt.parent_comment_id,
		comment_id: cmt.comment_id,
		commented_id: cmt.commented_id,
		entry_title: cmt.entry_title,
		boo_count: cmt.boos,
		woo_count: cmt.woos,
		comment_text: cmt.text,
		user_pic: cmt.pic,
		comment_date: cmt.created,
		commentor_id: cmt.commentor_id,
		comment_method: 'Sparcq',
		username: cmt.name,
		user_link: Sparcq.SQ.userURL(cmt.commentor_id)
	},page_num);

};

Sparcq.Comments.prototype.addComments = function(cmts,page_num) {

	/*

	First load all comments then init the post unnested comment

	*/
	
	for (var i = 0; i < cmts.length; i++) {
		var cmt = cmts[i];
		this.addCommentFromApi(cmt,page_num,true);
	};

	if (this.firstLoad) {
		if (this.listType == 'topic' ) { 
			this.addPostCommentEvent();
		}
	}

	this.updateReplyCounts();	
};

Sparcq.Comments.prototype.updateReplyCounts = function(cmt_id) {
	if (cmt_id) {
		jQuery('#' + cmt_id + ' .num_replies:first').html(this.replyCounts[cmt_id] || 0);
	} else {
		for (var id in this.replyCounts) {
			this.updateReplyCounts(id);
		}
	}
};

Sparcq.Comments.prototype.addPostCommentEvent = function() {
	var self = this;
	jQuery('#post_unnested_comment_holder').show();
	jQuery('#post_comment_holder img').click(function() {
		self.postComment();
	});

};


Sparcq.Comments.prototype.removePostCommentEvent = function() {
	jQuery('#post_comment_holder img').unbind('click');
};


Sparcq.Comments.prototype.hide = function() {
	var comment_list = jQuery('#ratings_comments');
	var comment_list_holder = jQuery('#ratings_comments_holder');
	//var rating_list = jQuery('#ratings_ratings');
	//var rating_list_holder = jQuery('#ratings_ratings_holder');
	comment_list_holder.removeClass('is_selected');
	comment_list_holder.addClass('is_not_selected');
	comment_list.hide();
	//rating_list_holder.removeClass('is_not_selected');
	//rating_list_holder.addClass('is_selected');
	//rating_list.show();

};

Sparcq.Comments.prototype.show = function() {
	var comment_list = jQuery('#ratings_comments');
	var comment_list_holder = jQuery('#ratings_comments_holder');
	//var rating_list = jQuery('#ratings_ratings');
	//var rating_list_holder = jQuery('#ratings_ratings_holder');
	//rating_list_holder.removeClass('is_selected');
	//rating_list_holder.addClass('is_not_selected');
	//rating_list.hide();
	comment_list_holder.removeClass('is_not_selected');
	comment_list_holder.addClass('is_selected');
	comment_list.show();
		
};


Sparcq.Comments.prototype.checkForAnchorScroll = function() {
	if (location.hash) {
		var id = location.hash;
		//alert(id);
	
		if (id.substr(0,5) == '#cmt_') {
			id = id.substr(5);
			jQuery('#ratings_comments_box').trigger('load', 'comments');
			this.openAndScrollToComment(id);
		} else if (id == '#comments') {
			jQuery('#ratings_comments_box').trigger('load', 'comments');
			Sparcq.SQ.scrollToElement(jQuery('#ratings_comments'),-100);
		}
	}
};

Sparcq.Comments.prototype.openAndScrollToComment = function(id) {
	this.expandComment(id);
	Sparcq.SQ.scrollToElement(jQuery('#' + id));
};

Sparcq.Comments.prototype.expandComment = function(id) {
	if (this.comments[id].parent_comment_id) {
		this.showReplies(this.comments[id].parent_comment_id);	
		this.expandComment(this.comments[id].parent_comment_id);
	}
}

Sparcq.Comments.prototype.getCommentLevel = function(id) {
	if (!this.comments[id]) {
		return null;
	}
	if (this.comments[id].parent_comment_id) {
		return 1 + this.getCommentLevel(this.comments[id].parent_comment_id);
	} else {
		return 0;
	}
};

Sparcq.Comments.prototype.getCommentColorClass = function(id) {
	if (!this.comments[id]) return null;
	var alts = [ 'F4EFE9', 'E3D7C8' ];
	if (!this.comments[id].parent_comment_id) {
		return alts[this.commentList.length % alts.length];
	} else {
		return alts[this.nestedComments[this.comments[id].parent_comment_id].length % alts.length];
	}
};

Sparcq.Comments.prototype.pushCommentObj = function(id,vars) {
	this.comments[id] = vars;
	if (vars.parent_comment_id) {
		var _p_id = vars.parent_comment_id;
		if (!this.nestedComments[_p_id]) {
			this.nestedComments[_p_id] = [];
		}
		this.nestedComments[_p_id].push(id);
	} else {
		this.commentList.push(id);
	}

};

Sparcq.Comments.prototype.addWooBooEvent = function(comment_id) {
	var comment_holder = jQuery('#' + comment_id);
	var self = this;
	jQuery('.woo_or_boo_holder', comment_holder).click(function(e) {
		var sh = jQuery(this);
		if ( (e.clientX - sh.offset().left) > 23 ) {
			self.rateComment('woo',comment_id);
		} else {
			self.rateComment('boo',comment_id);
		}
	});
};

Sparcq.Comments.prototype.handleRateComment = function(ret,wb_type,comment_id) {
    var comment = ret.parsed_return;
	jQuery('.woo_holder', jQuery('#comment_container_' + comment_id) ).html(
	    comment.woos
	);
	jQuery('.boo_holder', jQuery('#comment_container_' + comment_id) ).html(
        comment.boos
	);
};

Sparcq.Comments.prototype.handleRateCommentError = function(error_msg) {
	alert(error_msg);
	//this.addPostCommentEvent();
};

Sparcq.Comments.prototype.rateComment = function(wb_type,comment_id) {
	var self = this;
	if ( !SPARCQ.SESSION.promptIfNotLoggedIn(function() {
		self.rateComment(wb_type,comment_id);
	}) ) {
		return false;
	}
	var text = jQuery('#post_comment_container textarea').val();
	SPARCQ.API.callMethod('comment.addRating', {
		params: {
			rating: wb_type,
			sparcq_member_id: SPARCQ.SESSION.getMemberId(),
			comment_id: comment_id	
		},
		onSuccess: function(ret) {
			self.handleRateComment(ret,wb_type,comment_id);
		},
		onError: function(ret,id) {
			self.handleRateCommentError('error adding rating for comment ' + comment_id);
		}
	});
};

Sparcq.Comments.prototype.updateCommentTotal = function() {
	jQuery('#total_comments_count').html(Sparcq.SQ.getCountDisplay('comment',this.totalComments));
};

Sparcq.Comments.prototype.initNode = function(vars) {	
	var self = this;

	var new_comment_holder = this.cloneItem.clone();
	new_comment_holder.removeClass('comment_and_replies_default');
	var _html_id = vars.comment_id;
	new_comment_holder.attr('id',_html_id);
	this.pushCommentObj(_html_id,vars);
	var append_box = null;
	var append_class = this.getCommentColorClass(vars.comment_id);
	var append_nested_level = this.getCommentLevel(vars.comment_id);

	var replies_holder = jQuery('.comment_replies .replies_holder',new_comment_holder);
	replies_holder.attr('id','replies_holder_' + vars.comment_id);
	var reply_box = jQuery('.comment_replies .post_reply', new_comment_holder);
	reply_box.attr('id','post_reply_' + vars.comment_id);

	//show topic title for user comment page
	if (this.listType == 'user') {
		jQuery('.comment_topic_link',new_comment).show();
	}

	var new_comment = jQuery('.comment_container',new_comment_holder);
	new_comment.attr('id','comment_container_' + vars.comment_id);
	//new_comment_holder.appendTo(append_box);
	new_comment.removeClass('E3D7C8');
	new_comment.removeClass('inner_0');

	
	new_comment.addClass(append_class);
	new_comment.addClass('inner_' + append_nested_level);
	

	return new_comment_holder;

};

Sparcq.Comments.prototype.addComment = function(vars,page_num)  {
	var new_comment_holder = this.initNode(vars,page_num);
	var new_comment = jQuery('.comment_container',new_comment_holder);

	var template_html = new_comment.html();
	var pic_html = "<img width='25' height='25' src='" + (vars.user_pic || Sparcq.SQ.uriFor(this.defaultUserIcon))+ "' />";
	new_comment.html(Sparcq.SQ.parseHtml(
		template_html, {
			boo_count: vars.boo_count,
			woo_count: vars.woo_count,
			comment_text: vars.comment_text,
			comment_date: vars.comment_date,
			comment_method: vars.comment_method,
			user_pic_image: pic_html,
			user_link: vars.user_link,
			comment_topic_link: (vars.entry_title) ? Sparcq.SQ.getWikiLink(vars.entry_title,'/' + vars.entry_title) : '',
			//comment_id: vars.comment_id,
			//parent_id: vars.parent_id || null,
			username: vars.username
		}
	));
	
	var self = this;

	//var new_comment_holder = jQuery('#' + vars.comment_id);
	var append_box = null;

	if (vars.parent_comment_id) {
		var parent_comment_holder = jQuery('#' + vars.parent_comment_id);
		var parent_comment = jQuery('.comment_container', parent_comment_holder);
	
		//append_box = jQuery('#replies_holder_' + vars.comment_id);
		append_box = jQuery('.comment_replies .replies_holder:first',parent_comment_holder)
		var show_hide_replies = jQuery('.show_hide_replies_buttons',parent_comment);
		
		if (show_hide_replies.css('display') == 'none') {
			show_hide_replies.css('display','block');
			var link = jQuery('a',show_hide_replies);
			link.click(function() {	
				self.toggleReplies(vars.parent_comment_id);
				return false;
			});
		}
	} else {
		//append_box = jQuery('.comments_outer_container');
		append_box = this.new_paginator.getPageNode(page_num);
	}

	
	new_comment_holder.appendTo(append_box);

	var post_replies = jQuery('.post_reply_button',new_comment);	
	var self = this;
	var post_reply_display = jQuery('.comment_replies .post_reply',new_comment.parent());
	post_reply_display.removeClass('reply_1');
	post_reply_display.addClass('reply_'+ this.getCommentLevel(vars.comment_id));
	post_replies.css('display','block');

	/*
	event for woo boo
	*/
	// Only people other than the comment maker should be able to WooBoo
	if ( !SPARCQ.SESSION.getMemberId() || SPARCQ.SESSION.getMemberId() != vars.commentor_id ) {
	    this.addWooBooEvent(vars.comment_id);
	}

	/* 
	links for showing/hiding reply box
	*/
	jQuery('a',post_replies).click(function() {	
		jQuery('.post_reply').each(function() {
			var el = jQuery(this);
			el.hide();
		});
		self.showPostReply(vars.comment_id,true);
		return false;
	});

	/*
	post reply submit
	*/

	var comment_container = new_comment.parent();
	jQuery('.post_reply_submit a',comment_container).click(function() {
		self.postReply( vars, comment_container );
		return false;
	});
	jQuery('#post_reply_cancel',comment_container).click(function() {
		var whatev = self.clearAndGetReplyText(vars,comment_container);
		return false;
	});

	new_comment.show();
	
	if (vars.entry_title && !SPARCQ.TOPIC_NAME) {
		jQuery('.comment_topic_link',new_comment).show();
	}
	
	return new_comment;

};

Sparcq.Comments.prototype.getRepliesNode = function(comment_id) {
	return jQuery('#replies_holder_' + comment_id);
};

Sparcq.Comments.prototype.toggleReplies = function(comment_id) {
	var replies = this.getRepliesNode(comment_id);
	if (replies.css('display') == 'none') {
		this.showReplies(comment_id);
	} else {
		this.hideReplies(comment_id);
	}
};

Sparcq.Comments.prototype.showReplies = function(comment_id) {
	var replies = this.getRepliesNode(comment_id);
	if (replies.css('display') == 'none') {	
		replies.toggle();
	}
};

Sparcq.Comments.prototype.hideReplies = function(comment_id) {
	var replies = this.getRepliesNode(comment_id);
	//hide children first
	jQuery('.comment_replies .replies_holder',replies).each(function() {
		var el = jQuery(this);
		el.hide();
	});
	replies.hide();
};

Sparcq.Comments.prototype.getPostReplyNode = function(comment_id) {
	return jQuery('#post_reply_' + comment_id);
};
Sparcq.Comments.prototype.hidePostReply = function(comment_id) {
	var reply = this.getPostReplyNode(comment_id);
	reply.hide();
	jQuery('#post_unnested_comment_holder').show();
};
Sparcq.Comments.prototype.showPostReply = function(comment_id,doScroll) {	
	var reply = this.getPostReplyNode(comment_id);
	jQuery('#post_unnested_comment_holder').hide();
	reply.show();
	jQuery('textarea',reply).focus();
	this.showReplies(comment_id);
	if (doScroll) {	
		Sparcq.SQ.scrollToElement(reply,-250);
	}
};

Sparcq.Comments.prototype.addCommentToEnd = function(ret) {	
	if ( this.new_paginator.checkPageCached(this.new_paginator.totalPages) ) {
		this.new_paginator.getPage(this.new_paginator.totalPages);
		this.addPostedComment(ret);
	} else {
		var self = this;
	
		this.new_paginator.getPage(this.new_paginator.totalPages,function() {
			self.addPostedComment(ret);
		});
	}
}

Sparcq.Comments.prototype.addPostedComment = function(ret) {
	ret = ret.parsed_return;
	this.addCommentFromApi(ret,this.new_paginator.totalPages);
	this.updateCommentTotal();
	jQuery('#post_comment_container textarea').val('');	
	this.addPostCommentEvent();
}

Sparcq.Comments.prototype.handlePostComment = function(ret) {
	
	if (!this.new_paginator.totalPages) {
		this.new_paginator.setTotalPages(1);
		this.new_paginator.createCachedPage({},1);
	}

	if (this.new_paginator.totalPages == this.new_paginator.currentPage) {
		this.addPostedComment(ret);
		return;
	}
	this.addCommentToEnd(ret);

};

Sparcq.Comments.prototype.handlePostCommentError = function(error_msg) {
	alert(error_msg);
	this.addPostCommentEvent();
};

Sparcq.Comments.prototype.handlePostReply = function(ret) {
	ret = ret.parsed_return;
	this.addCommentFromApi(ret);
	this.updateReplyCounts(ret.parent_comment_id);
	this.updateCommentTotal();
	//jQuery('#post_comment_container textarea').val('');	
	//this.addPostCommentEvent();
};

Sparcq.Comments.prototype.handlePostReplyError = function(error_msg) {
	alert(error_msg);
	//this.addPostCommentEvent();
};



Sparcq.Comments.prototype.postComment = function() {
	var self = this;
	if ( !SPARCQ.SESSION.promptIfNotLoggedIn(function() {
		self.postComment();
	}) ) {
		return false;
	}
	var text = jQuery('#post_comment_container textarea').val();
	if (!text || text == '') {
		alert("You cannot post a blank comment!");
		return;
	}
	this.removePostCommentEvent();
	var self = this;

	SPARCQ.API.callMethod('topic.addComment', {
		params: {
			entry_id: this.objectId,
			sparcq_member_id: SPARCQ.SESSION.getMemberId(),
			comment_text: text	
		},
		onSuccess: function(ret) {
			self.handlePostComment(ret);
		},
		onError: function(ret,id) {
			self.handlePostCommentError('error posting comment for ' + id);
		}
	});

	SPARCQ.TRACKING.trackComment(SPARCQ.TOPIC_NAME);
};

Sparcq.Comments.prototype.clearAndGetReplyText = function(vars,comment_container) {
	var text = jQuery('#post_comment_container textarea').val();
	var c_level = this.getCommentLevel(vars.comment_id);
	var reply_class = 'reply_' + c_level; 
	var text = jQuery('.comment_replies .post_reply.'+reply_class+' textarea',comment_container).val();
	jQuery('.comment_replies .post_reply.'+reply_class+' textarea',comment_container).val('');

	this.hidePostReply(vars.comment_id);
	return text;
}

Sparcq.Comments.prototype.postReply = function(vars,comment_container) {
	var self = this;
	if ( !SPARCQ.SESSION.promptIfNotLoggedIn(function() {
		self.postReply(vars,comment_container);
	}) ) {
		return false;
	}

	var text = this.clearAndGetReplyText(vars,comment_container);
	var self = this;

	SPARCQ.API.callMethod('topic.addComment', {
		params: {
			entry_id: vars.commented_id || this.objectId,
			sparcq_member_id: SPARCQ.SESSION.getMemberId(),
			parent_comment_id: vars.comment_id,
			comment_text: text	
		},
		onSuccess: function(ret) {
			self.handlePostReply(ret);
		},
		onError: function(ret,id) {
			self.handlePostReplyError('error posting comment for ' + id);
		}
	});

	SPARCQ.TRACKING.trackComment(vars.entry_title);
};

