var Comments = function() {
	var $S = CBC.SETTINGS;
	var $U = CBC.UTIL;
	var $E = CBC.EVENT;
	var $D = CBC.DOM;
	var $ = $U.getElementsById;
	var SETTINGS = { cookie_sort_name: "cmt-sort", comments_rendered: false, jump_allowed: true, story_width: 606, story_margin_left:5, tpl_socialcomments: null };
	var paginator = { number_of_items: 0, number_of_pages: 0, number_per_page: 5, current_page: 1, anchor:"socialcomments", sort:'' };

	return {

		init: function() {
			try {
				if ($S.getVal("cmtDefaultTemplates")) CBC.loadAssets({_src:'/includes/objects/pluck/config/templates-comments.js', _id:'templates-comments-js'});
				if ($S.getVal("cid") == "(none)" || !$S.getVal("cmtOnLoad")) return;
				this.getData();
			} catch(e) {
				$U.debug(e);
			}
		},

		getData: function(_o) {
			try {
				if (!$S.getVal("cid")) return;
				if (_o && _o._el) {
					if (_o._el.className.indexOf("active") > -1) return;
					this.setActivePage(_o._el,_o.on_page);
					if (paginator.sort != _o.sort) {
						$D.removeClass('sort-'+paginator.sort,"active");
						$D.addClass('sort-'+_o.sort,"active");
					}
				}

				var sort_cookie = $U.readCookie(SETTINGS.cookie_sort_name);
				paginator.current_page = (!_o||_o.on_page == null) ? paginator.current_page : _o.on_page;
				paginator.sort = (!_o||_o.sort == null) ? $S.getVal("cmtSort") : _o.sort;
				paginator.sort = (sort_cookie) ? sort_cookie : $S.getVal("cmtSort");

				var rb = new RequestBatch();
				var ak = new ArticleKey($S.getVal("cid"));
				var ro = new CommentPage(ak,$S.getVal("cmtPerPage"),paginator.current_page,paginator.sort);
				rb.AddToRequest(ro);
				rb.BeginRequest($S.getVal("serverUrl"),this.handleData);

			} catch(e) {
				$U.debug(e);
			}
		},

		handleData: function(rbatch) {
			try {
				var commentPage = rbatch.Responses[0].CommentPage;

				if (!SETTINGS.tpl_socialcomments) {
					SETTINGS.tpl_socialcomments = new $U.Template($S.getVal("tpl_socialcomments"));
					var tpl_data = {};
					tpl_data.NumberOfComments = commentPage.NumberOfComments;
					tpl_data.maxCmtLength = $S.getVal("maxCmtLength");
					tpl_data.ArticleType = $U.ucfirst($S.getVal("articleType"));
					$('socialcomments').innerHTML = SETTINGS.tpl_socialcomments.evaluate(tpl_data);
				}

				$('sort-'+paginator.sort).className = "active";
				$('articlecomments').className = (parseInt(commentPage.NumberOfComments) == 0) ? "d-none" : "d-block";
				var cmt_html = '';
				var cmt_tpl_data = [];
				cmt_tpl_data["comments"] = [];
				cmt_tpl_data.ArticleKey = commentPage.ArticleKey.Key;

				var tpl_cmt = new $U.Template($S.getVal("tpl_cmt"));
				var tpl_cmt_blocked = new $U.Template($S.getVal("tpl_cmt_blocked"));

				var rb_disagree = new RequestBatch();

				for (var i=0; i < commentPage.Comments.length; i++) {
					//get initial comments
					var cKey = commentPage.Comments[i].CommentKey.Key;
					if (!cmt_tpl_data[cKey]) cmt_tpl_data[cKey] = {};

					cmt_tpl_data[cKey].NumberOfRecommendations = parseInt(commentPage.Comments[i].NumberOfRecommendations);
					cmt_tpl_data[cKey].NumberOfDisagreements = 0;
					cmt_tpl_data[cKey].People = (cmt_tpl_data[cKey].NumberOfRecommendations < 2) ? "Person" : "People";
					cmt_tpl_data[cKey].CommentKey = cKey;
					cmt_tpl_data[cKey].CommentBody = commentPage.Comments[i].CommentBody.replace(/\n/g,"<br/>");
					cmt_tpl_data[cKey].CommentBody = cmt_tpl_data[cKey].CommentBody.replace(/\$/g,"&#36;");
					cmt_tpl_data[cKey].CommentAuthorId = commentPage.Comments[i].Author.UserKey.Key;
					cmt_tpl_data[cKey].DisplayName = commentPage.Comments[i].Author.DisplayName;
					cmt_tpl_data[cKey].PostedAtTime = CBC.APP.PLUCK.Comments.formatTimeStamp(commentPage.Comments[i].PostedAtTime);
					cmt_tpl_data[cKey].ContentBlockingState = commentPage.Comments[i].ContentBlockingState;
					cmt_tpl_data[cKey].logic = {};
					cmt_tpl_data[cKey].logic.Recommended = commentPage.Comments[i].CurrentUserHasRecommended.toLowerCase();
					cmt_tpl_data[cKey].logic.Reported = commentPage.Comments[i].CurrentUserHasReportedAbuse.toLowerCase();
					cmt_tpl_data[cKey].logic.isOddRow = (i%2 == 0) ? "false" : "true";
					if (cmt_tpl_data[cKey].logic.Recommended == "true") cmt_tpl_data[cKey].RecommendAction = "agree";
					cmt_tpl_data["comments"].push(cKey);

					//build request batch for disagreements
					rb_disagree.AddToRequest(new ArticleKey(cKey));
				}

				rb_disagree.BeginRequest($S.getVal("serverUrl"), function(rbatch) {
					//update cmt_tpl_data disagreements
					for (var i=0; i < rbatch.Responses.length; i++) {
						var article = rbatch.Responses[i].Article;
						var cKey = article.ArticleKey.Key;
						cmt_tpl_data[cKey].NumberOfDisagreements = parseInt(article.Recommendations.NumberOfRecommendations);
						cmt_tpl_data[cKey].logic.Recommended = (cmt_tpl_data[cKey].logic.Recommended == "true") ? "true" : article.Recommendations.CurrentUserHasRecommended.toLowerCase();
						if (article.Recommendations.CurrentUserHasRecommended.toLowerCase() == "true") cmt_tpl_data[cKey].RecommendAction = "disagree";
					}

					//evaluate templates
					for (var i=0; i < cmt_tpl_data["comments"].length; i++) {
						var cKey = cmt_tpl_data["comments"][i];
						cmt_html += (cmt_tpl_data[cKey].ContentBlockingState == "Unblocked") ? tpl_cmt.evaluate(cmt_tpl_data[cKey],cmt_tpl_data[cKey].logic) : tpl_cmt_blocked.evaluate(cmt_tpl_data[cKey],cmt_tpl_data[cKey].logic);
					}

					$('cmt-wrapper').innerHTML = cmt_html;
					$('socialcomments-submit').className = "d-block";
					CBC.APP.PLUCK.Comments.setScreenFog(0);

				});

				//paginator
				paginator.current_page = parseInt(commentPage.OnPage);
				paginator.number_of_items = parseInt(commentPage.NumberOfComments);
				paginator.number_of_pages = Math.ceil(paginator.number_of_items / paginator.number_per_page);
				var tpl_prefix = 'onclick="CBC.APP.PLUCK.Comments.getData({articleKey:\'' + cmt_tpl_data.ArticleKey + '\', on_page:';
				var tpl_suffix = ', sort:\'' + paginator.sort + '\', _el:this});"';
				var tpls = {li: new $U.Template($S.getVal("tpl_paginator_li")),
										li_attrib: new $U.Template(tpl_prefix + '#{pageNumber}' + tpl_suffix),
										li_prev_on: new $U.Template($S.getVal("tpl_paginator_li_prev_on")),
										li_prev_attrib: new $U.Template(tpl_prefix + '#{prevPage}' + tpl_suffix),
										li_prev_off: new $U.Template($S.getVal("tpl_paginator_li_prev_off")),
										li_next_on: new $U.Template($S.getVal("tpl_paginator_li_next_on")),
										li_next_attrib: new $U.Template(tpl_prefix + '#{nextPage}' + tpl_suffix),
										li_next_off: new $U.Template($S.getVal("tpl_paginator_li_next_off")),
										li_first: new $U.Template($S.getVal("tpl_paginator_li_first")),
										li_first_attrib: new $U.Template(tpl_prefix + '#{firstPage}' + tpl_suffix),
										li_first_off: new $U.Template($S.getVal("tpl_paginator_li_first_off")),
										li_last: new $U.Template($S.getVal("tpl_paginator_li_last")),
										li_last_attrib: new $U.Template(tpl_prefix + '#{lastPage}' + tpl_suffix),
										li_last_off: new $U.Template($S.getVal("tpl_paginator_li_last_off"))};
				if (paginator.number_of_pages > 1) $('cmt-paginator').innerHTML = CBC.APP.PLUCK.Comments.getPaginatorHtml(paginator,tpls);

				//hide report abuse
				if ($('cmt-abusereport')) $('cmt-abusereport').className += " d-none";

				//handle comments list
				if ( new Date($S.getVal("scped")) < new Date() ) {
					$('socialcomments-submit').innerHTML = (parseInt(commentPage.NumberOfComments) > 0) ? '<p class="cmt-note">' + CBC.APP.PLUCK.Comments.translateMsg($S.getVal("seMsg")) + '</p><p class="disclaimer">Note: The CBC does not necessarily endorse any of the views posted. Please note that comments are published according to our <a href="/aboutcbc/discover/submissions.html" target="_blank">submission guidelines</a>.</p>' : '';
				} else {
					var at = $U.getObjectFromCookie('at');
					if (at) {
						var pd = $U.getObjectFromCookie('pd');
						if (!pd.FirstName || !pd.LastName || !pd.City || !(pd.Province || pd.Country) ) {
							$('socialcomments-submit').innerHTML =  '<h4>&nbsp;</h4><span id="cmt-post-statusbox" class="d-block">You need to <a href="/membercentre/EditProfile.aspx">update your profile</a> to post a comment.</span>';
						}
					}

					var comment_chars_count = $U.getElementsByClassName("comment-chars-count",$('cmt-form-label'))[0];
					comment_chars_count.style.display = "none";
					$('cmt-post-textarea').value = "";

					if (CBC.APP.PLUCK.isLoggedIn()) {
						$('cmt-post-textarea').disabled = false;
						$('cmt-post-button').disabled = false;
						$E.on('cmt-post-textarea',"click", function(o) { comment_chars_count.style.display = "inline"; });
						$E.on('cmt-post-textarea',"blur", function(o) { comment_chars_count.style.display = "none"; });
					} else {
						$('cmt-post-button').className = "off";
						$('cmt-post-statusbox').innerHTML = $S.getVal("cmt-post-statusbox-notloggedin");
						$('cmt-post-statusbox').className += " d-block";
					}

				}

				SETTINGS.comments_rendered = true;

				if (SETTINGS.jump_allowed) CBC.APP.PLUCK.Comments.handleJump();

			} catch(e) {
				$U.debug(e);
			}
		},

		submit: function() {
			try {
				var _el = $('cmt-post-textarea');

				if ($U.trim(_el.value).length == 0) {
					$('cmt-post-statusbox').innerHTML = "Please type in a comment";
					$('cmt-post-statusbox').className += " d-block";
					_el.focus();
				} else if (_el.value.length < $S.getVal("maxCmtLength")) {
					var rb = new RequestBatch();
					var ak = new ArticleKey($S.getVal("cid"));
					var ca = new CommentAction(ak, document.location.href, document.title, _el.value);
					rb.AddToRequest(ca);
					rb.BeginRequest($S.getVal("serverUrl"),this.handleSubmit);
				} else {
					$('cmt-post-statusbox').innerHTML = $S.getVal("cmt-post-statusbox-maxchars");
					$('cmt-post-statusbox').className += " d-block";
					_el.focus();
				}

			} catch(e) {
				$U.debug(e);
			}

		},

		handleSubmit: function(rbatch) {
			try {
				if (rbatch.Messages[0].Message == 'ok') {
					$('cmt-form-wrapper').className += " d-none";
					$('cmt-post-statusbox').innerHTML = $S.getVal("cmt-post-statusbox-posted");
				} else {

					switch (rbatch.Messages[0].Message) {
						case "We restrict rapid posting of multiple comments for quality reasons. You have already posted a comment within the last several seconds. Please try again later.":
							$('cmt-post-statusbox').innerHTML = rbatch.Messages[0].Message;
							break;
						case "Comment submission denied by authentication level: Weak":
							$('cmt-post-statusbox').innerHTML = 'Your session has expired.  Please <a href="/sso/SSOAuthenticationDomain.ashx?mode=Login&amp;redirecturl='+document.location.href+'#socialcomments-submit">log in</a> again';
							break;
						default:
							$('cmt-post-statusbox').innerHTML = 'Your session has expired.  Please <a href="/sso/SSOAuthenticationDomain.ashx?mode=Login&amp;redirecturl='+document.location.href+'#socialcomments-submit">log in</a> again';
							break;
					}

				}
				$('cmt-post-statusbox').className += " d-block";
			} catch(e) {
				$U.debug(e);
			}
		},

		agree: function(_el,_cid) {
			try {
				this.updateUI(_el, true);
				var rb = new RequestBatch();
				var ckey = new CommentKey(_cid);
				var ra = new RecommendAction(ckey);
				rb.AddToRequest(ra);
				rb.BeginRequest($S.getVal("serverUrl"),function(o){});
			} catch(e) {
				$U.debug(e);
			}
		},

		disagree: function(_el,_cid) {
			try {
				this.updateUI(_el, false)
				var rb = new RequestBatch();
				var ckey = new ArticleKey(_cid);
				var ra = new RecommendAction(ckey);
				rb.AddToRequest(ra);
				rb.BeginRequest($S.getVal("serverUrl"),function(o){});
			} catch(e) {
				$U.debug(e);
			}
		},

		updateUI: function(_el, agree_flag) {
			try {
				var _cmd = $D.getAncestorByClassName(_el,"cmd");
				var count = parseInt(_el.firstChild.innerHTML);
				count = (count > 0) ? ++count : 1;

				//left col
				var _a = $U.getElementsByClassName("up",_cmd,"li")[0].firstChild;
				var _strong = document.createElement("strong");
				_strong.innerHTML = (agree_flag) ? "<em>" + count + "</em>" : _a.innerHTML;
				_a.parentNode.appendChild(_strong);
				_a.parentNode.removeChild(_a);

				var _a = $U.getElementsByClassName("down",_cmd,"li")[0].firstChild;
				var _strong = document.createElement("strong");
				_strong.innerHTML = (agree_flag) ? _a.innerHTML : "<em>" + count + "</em>";
				_a.parentNode.appendChild(_strong);
				_a.parentNode.removeChild(_a);

				//right col
				var _a = $U.getElementsByClassName("tup",_cmd)[0];
				var _em = document.createElement("em");
				_em.innerHTML = 'You <strong>' + ((agree_flag) ? "agree" : "disagree" ) + '</strong> with this comment';
				_a.parentNode.insertBefore(_em,_a);
				_a.parentNode.removeChild(_a);
				var _a = $U.getElementsByClassName("tdown",_cmd)[0];
				_a.parentNode.removeChild(_a);
			} catch(e) {
				$U.debug(e);
			}

		},

		spawnAbuse: function(_el,_articleId) {
			try {
				var _offset = $($S.getVal("cmtAbuseReportWrapperOffset"));
				var wrapper_id = 'cmt-abusereport';
				if (!$(wrapper_id)) {
					var _div = document.createElement('DIV');
					_div.id = wrapper_id;
					_div.innerHTML = $S.getVal("tpl_cmtAbuseReport");
					document.getElementsByTagName('BODY')[0].appendChild(_div);
					$E.addListener('cmt-abusereport-submit','click',this.submitAbuse,{cid:_articleId},this);
				} else {
					$E.removeListener('cmt-abusereport-submit');
					$E.addListener('cmt-abusereport-submit','click',this.submitAbuse,{cid:_articleId},this);
				}
				$('cmt-abusereport-statusbox').className = "d-none";
				$('cmt-abusereport-type').className = "";
				$(wrapper_id).className = " d-block";
				$D.setXY(wrapper_id,[$D.getX(_el)-_offset[0],$D.getY(_el)-_offset[1]]);
				_el.blur();

			} catch(e) {
				$U.debug(e);
			}
		},

		submitAbuse: function(_e,_o) {
			try {
				if ($('cmt-abusereport-type').value == "") {
					$('cmt-abusereport-statusbox').className = "d-inline";
					$('cmt-abusereport-type').className = "error";
				} else {
					var rb = new RequestBatch();
					var _key  = new CommentKey(_o.cid);
					var _type = $('cmt-abusereport-type').options[$('cmt-abusereport-type').selectedIndex].value;
					var _desc = $('cmt-abusereport-comment').value;
					var raa = new ReportAbuseAction(_key, _type, _desc);
					rb.AddToRequest(raa);
					$D.addClass('cmt-abusereport','sending');
					rb.BeginRequest($S.getVal("serverUrl"),this.handleAbuse);
				}
			} catch(e) {
				$U.debug(e);
			}
		},

		closeAbuse: function() {
			$('cmt-abusereport').className = "d-none";
			$D.removeClass('cmt-abusereport-type',"error");
			$D.removeClass('cmt-abusereport-statusbox',"d-inline");
			$('cmt-abusereport-type').selectedIndex = 0;
			$('cmt-abusereport-comment').value = "";
		},

		handleAbuse: function(responseBatch) {
			$('cmt-abusereport').className += " d-none";
			CBC.APP.PLUCK.Comments.getData();
		},

		sortComments: function(_el,sort) {
			try {
				if ($U.readCookie(SETTINGS.cookie_sort_name)) {
					if ($U.readCookie(SETTINGS.cookie_sort_name) == sort) return;
					$U.eraseCookie(SETTINGS.cookie_sort_name);
					$U.createCookie(SETTINGS.cookie_sort_name,sort,30);
				} else {
					$U.createCookie(SETTINGS.cookie_sort_name,sort,30);
				}
				SETTINGS.jump_allowed = false;
				CBC.APP.PLUCK.Comments.getData({sort:sort,on_page:1,_el:_el});
			} catch(e) {
				$U.debug(e);
			}
		},

		formatTimeStamp: function(timestamp) {
			try {
				var date = new Date(timestamp);
				var _month = "0"+(parseInt(date.getMonth())+1);
				_month = _month.substring(_month.length-2,_month.length);
				var _mins = "0"+date.getMinutes();
				_mins = _mins.substring(_mins.length-2,_mins.length);
				var _time = (date.getHours() < 12) ? ( ((date.getHours() == 0) ? 12 : date.getHours() )+":"+_mins+" AM ET") : ( (date.getHours() == 12) ? (date.getHours()): (date.getHours()-12) ) +":"+_mins+" PM ET";
				var _date = "0"+date.getDate();
				_date = _date.substring(_date.length-2,_date.length);
				var _ts = date.getFullYear()+ "/" + _month + "/" + _date + "<br/>at " + _time;
				return _ts;
			} catch(e) {
				$U.debug(e);
				return "";
			}
		},

		handleCommentsEntry: function(el) {
			try {
				if (el.value.length >= parseInt($S.getVal("maxCmtLength"))) {
					el.value = el.value.substr(0,parseInt($S.getVal("maxCmtLength"))-1);
				} else {
					$('cmtCharCount').innerHTML = (el.value.length < 0) ? 0 : parseInt($S.getVal("maxCmtLength")) - (el.value.length+1);
				}
			} catch(e) {
				$U.debug(e);
			}
		},

		focusCommentForm: function() {
			if (!$('cmt-post-textarea').disabled) {
				setTimeout("document.getElementById('cmt-post-textarea').focus()",10);
				$U.getElementsByClassName("comment-chars-count",$('cmt-form-label'))[0].style.display = "inline";
			}
		},

		handleJump: function() {
			var _split = (''+document.location).split('#');
			if (_split.length > 1) {
				var jump_id = _split[_split.length-1];
				if (jump_id) window.scrollTo(0,$D.getY($(jump_id)));
			}
			SETTINGS.jump_allowed = true;
		},

		getDataFromId: function(_id,_obj) { //_obj: update_article, mv_url, mv_title, mv_section, mv_cat
			if (_id) {
				CBC.SETTINGS.setVal('cid',_id);

				if (_obj.update_article) {
					if (_obj.mv_url && _obj.mv_title) {
						var categories = new Array();
						for (var i=0; i<_obj.mv_cat.length; i++) categories[i] = new Category(_obj.mv_cat[i]);

						var rb = new RequestBatch();
						var ua;
						if (_obj.mv_section && categories.length > 0)
							ua = new UpdateArticleAction(new ArticleKey(_id), _obj.mv_url, _obj.mv_title, new Section(_obj.mv_section), categories);
						else if (_obj.mv_section && categories.length == 0)
							ua = new UpdateArticleAction(new ArticleKey(_id), _obj.mv_url, _obj.mv_title, new Section(_obj.mv_section));
						else if (!_obj.mv_section && categories.length == 0)
							ua = new UpdateArticleAction(new ArticleKey(_id), _obj.mv_url, _obj.mv_title);

						rb.AddToRequest(ua);
						rb.BeginRequest(CBC.SETTINGS.getVal('serverUrl'), itemUpdated);
					}
				} else {
					this.getData();
				}

			}

			function itemUpdated(rbatch) {
				if (rbatch.Messages[0].Message == 'ok') CBC.APP.PLUCK.Comments.getData();
			}

		},

		getJumpAllowed: function() {
			return SETTINGS.jump_allowed;
		},

		setJumpAllowed: function(bool) {
			SETTINGS.jump_allowed = bool;
		},

		setActivePage: function(_el,_num) {
			try {
				_num = parseInt(_num);
				var _ul = $D.getAncestorByTagName(_el,"ul");
				var _pages = $U.getElementsByClassName("page",_ul,"li");
				for (var i=0; i<_pages.length; i++) {
					_pages[i].getElementsByTagName("a")[0].className = "";
					if (_pages[i].getElementsByTagName("a")[0].innerHTML == _num) _pages[i].getElementsByTagName("a")[0].className = "active";
				}
				this.setScreenFog(2);
			} catch(e) {
				$U.debug(e);
			}
		},

		setScreenFog: function(mode) {
			try {
				if (!$('fog')) {
					var _div = document.createElement("div");
					_div.id = "fog";
					document.body.appendChild(_div);
				}
				$('fog').removeAttribute("style");
				$D.removeClass('fog',"loading");

				switch (mode) {
					case 0:
						var _display = "none";
						break;
					case 1:
						var _display = "block";
						break;
					case 2:
						var y_0 = $D.getY("cmt-wrapper");
						var y_1 = $D.getY("socialcomments-submit");
						var pfheight = 0;
						if (y_0 && y_1) {
							pfheight = y_1 - y_0;
						}
						var _display = "block";
						var vpheight = $D.getViewportHeight();
						var _y = (pfheight < vpheight) ? pfheight/2 - 50 : vpheight/2;
						$D.setStyle('fog',"top",y_0+"px");
						$D.setStyle('fog',"left",SETTINGS.story_margin_left+"px");
						$D.setStyle('fog',"height",pfheight+"px");
						$D.setStyle('fog',"width",SETTINGS.story_width+"px");
						$D.setStyle('fog',"backgroundPosition",'center ' + _y + 'px');
						$D.addClass('fog',"loading");
						break;
					default:
						var _display = "none";
						break;
				}
				$D.setStyle('fog',"display",_display);
			} catch(e) {
				$U.debug(e);
			}
		},

		getPaginatorHtml: function(paginator, tpls) {
			try {
				var tpl_paginator_li = tpls.li;
				var tpl_paginator_li_attrib = tpls.li_attrib;
				var tpl_paginator_li_prev_on = tpls.li_prev_on;
				var tpl_paginator_li_prev_attrib = tpls.li_prev_attrib;
				var tpl_paginator_li_prev_off = tpls.li_prev_off;
				var tpl_paginator_li_next_on = tpls.li_next_on;
				var tpl_paginator_li_next_attrib = tpls.li_next_attrib;
				var tpl_paginator_li_next_off = tpls.li_next_off;
				var tpl_paginator_li_first = tpls.li_first;
				var tpl_paginator_li_first_attrib = tpls.li_first_attrib;
				var tpl_paginator_li_first_off = tpls.li_first_off;
				var tpl_paginator_li_last = tpls.li_last;
				var tpl_paginator_li_last_attrib = tpls.li_last_attrib;
				var tpl_paginator_li_last_off = tpls.li_last_off;
				var pages = Math.ceil(paginator.number_of_items / paginator.number_per_page);
				if (pages == 1) return "";
				var lis_html = '';

				var page_tpl_data = {};
				page_tpl_data.itemKey = paginator.itemKey;
				//page_tpl_data.sort = paginator.sort;
				page_tpl_data.anchor = paginator.anchor;

				page_tpl_data.prevPage = (paginator.current_page > 1) ? paginator.current_page-1 : paginator.current_page;
				page_tpl_data.nextPage = (paginator.current_page < pages) ? paginator.current_page+1 : paginator.current_page;
				page_tpl_data.firstPage = 1;
				page_tpl_data.lastPage = pages;
				page_tpl_data.attrib = tpl_paginator_li_attrib.evaluate(page_tpl_data);

				var page_start = paginator.current_page-5;
				var page_end = paginator.current_page+4;
				while (page_end > pages) { page_end--; page_start--; }
				while (page_start < 1) { page_start++; page_end++; }
				if (page_end > pages) page_end = pages;

				for (var i=page_start; i<=page_end; i++) {
					page_tpl_data.pageNumber = i;
					page_tpl_data.activeClass	= (i == paginator.current_page) ? 'active' : '';
					lis_html += tpl_paginator_li.evaluate(page_tpl_data);
				}

				//prev & next
				page_tpl_data.attrib = tpl_paginator_li_prev_attrib.evaluate(page_tpl_data);
				var li_prev_html = (paginator.current_page > 1) ? tpl_paginator_li_prev_on.evaluate(page_tpl_data) : tpl_paginator_li_prev_off.evaluate(page_tpl_data);
				page_tpl_data.attrib = tpl_paginator_li_next_attrib.evaluate(page_tpl_data);
				var li_next_html = (paginator.current_page < pages) ? tpl_paginator_li_next_on.evaluate(page_tpl_data) : tpl_paginator_li_next_off.evaluate(page_tpl_data);

				//first & last
				page_tpl_data.attrib = tpl_paginator_li_first_attrib.evaluate(page_tpl_data);
				var li_first_html = (paginator.current_page > 1) ? tpl_paginator_li_first.evaluate(page_tpl_data) : tpl_paginator_li_first_off.evaluate(page_tpl_data);;
				page_tpl_data.attrib = tpl_paginator_li_last_attrib.evaluate(page_tpl_data);
				var li_last_html = (paginator.current_page < pages) ? tpl_paginator_li_last.evaluate(page_tpl_data) : tpl_paginator_li_last_off.evaluate(page_tpl_data);;
				if (paginator.number_of_pages < 11) {
					li_first_html = li_last_html = "";
				}
				return '<ul class="paginator">' + li_first_html + li_prev_html + lis_html + li_next_html + li_last_html + '</ul>';

			} catch(e) {
				this.debug(e);
				return "";
			}

		},

		translateMsg: function(str) {
			try {
				return str.replace(/\[B\]/gi,"<strong>").replace(/\[\/B\]/gi,"</strong>").replace(/\n/gi,"<br/>");
			} catch(e) {
				$U.debug(e);
				return "";
			}

		}

	}
};
CBC.register({_name:'Comments',_class:Comments,_nameSpace: CBC.APP.PLUCK});

//comments
$S.setVal("tpl_socialcomments",'<div id="articlecomments"><h4 class="icon">#{ArticleType} comments (<em class="cmt">#{NumberOfComments}</em>)</h4><div id="cmt-sort-wrapper"><span>Sort:</span> <a class="" id="sort-TimeStampDescending" href="#" onclick="CBC.APP.PLUCK.Comments.sortComments(this,\'TimeStampDescending\');return false;">Most recent</a> | <a class="" id="sort-TimeStampAscending" href="#" onclick="CBC.APP.PLUCK.Comments.sortComments(this,\'TimeStampAscending\');return false;">First to last</a> | <a id="sort-RecommendationsDescending" href="#" onclick="CBC.APP.PLUCK.Comments.sortComments(this,\'RecommendationsDescending\');return false;">Agreed</a></div><div id="cmt-wrapper" class="clearfix">&nbsp;</div><div id="cmt-paginator"></div></div><a name="postc"></a><div id="socialcomments-submit">' + ( ($S.getVal("spMsg") != "(none)" && $S.getVal("spMsg") ) ? '<p class="cmt-note">'+CBC.APP.PLUCK.Comments.translateMsg($S.getVal("spMsg"))+'</p>' : "" ) + '<h4>Post your comment</h4><p class="disclaimer">Note: The CBC does not necessarily endorse any of the views posted. By submitting your comments, you acknowledge that CBC has the right to reproduce, broadcast and publicize those comments or any part thereof in any manner whatsoever. Please note that comments are pre-moderated/reviewed and published according to our <a href="/aboutcbc/discover/submissions.html" target="_blank">submission guidelines</a>.</p><span id="cmt-post-statusbox"></span><div id="cmt-form-wrapper"><div id="cmt-form-label" class="clearfix"><span class="label">Comment:</span><span class="comment-chars-count">Characters allowed: <em id="cmtCharCount">#{maxCmtLength}</em></span></div><textarea disabled="disabled" id="cmt-post-textarea" rows="10" cols="60" onkeypress="CBC.APP.PLUCK.Comments.handleCommentsEntry(this);"></textarea><span class="cmd"><button disabled="disabled" id="cmt-post-button" onclick="CBC.APP.PLUCK.Comments.submit();return false;">Post</button><a href="/aboutcbc/discover/submissions.html" target="_blank">Submission policy</a></span></div></div>');
$S.setVal("tpl_cmt",'<div class="comment #[isOddRow: {false:||true:odd}] clearfix"><div class="clearfix"><span><strong><a href="/membercentre/ViewMember.aspx?u=#{CommentAuthorId}" title="View #{DisplayName}&#039;s Page" target="_blank"><em>#{DisplayName}</em></a> wrote:</strong>Posted #{PostedAtTime}</span><span class="r">#{CommentBody}</span></div><div class="cmd clearfix"><span><ul class="thumb">#[Recommended: {false:<li class="up"><a onclick="CBC.APP.PLUCK.Comments.agree(this,\'#{CommentKey}\');this.blur();return false;" title="Agree" href="#"><em>#{NumberOfRecommendations}</em></a></li><li class="down"><a onclick="CBC.APP.PLUCK.Comments.disagree(this,\'#{CommentKey}\');this.blur();return false;" title="Disagree" href="#"><em>#{NumberOfDisagreements}</em></a></li></ul></span><span class="r"><a class="tup" onclick="CBC.APP.PLUCK.Comments.agree(this,\'#{CommentKey}\');this.blur();return false;" href="#"><em>#{NumberOfRecommendations}</em>Agree</a> <a class="tdown" href="#" onclick="CBC.APP.PLUCK.Comments.disagree(this,\'#{CommentKey}\');this.blur();return false;"><em>#{NumberOfDisagreements}</em>Disagree</a>||true:<li class="up"><strong><em>#{NumberOfRecommendations}</em></strong></li><li class="down"><strong><em>#{NumberOfDisagreements}</em></strong></li></ul></span><span class="r"><em>You <strong>#{RecommendAction}</strong> with this comment</em> }]<a class="policy" href="/aboutcbc/discover/submissions.html" target="_blank">Policy</a> #[Reported: {false:<a class="report" onclick="CBC.APP.PLUCK.Comments.spawnAbuse(this,\'#{CommentKey}\');return false;" href="#">Report abuse</a>||true:<span>Reported </span>}]</span></div></div>');
$S.setVal("tpl_cmt_blocked",'<div class="comment #[isOddRow: {false:||true:odd}] clearfix"><div class="clearfix"><span><strong><a href="/membercentre/ViewMember.aspx?u=#{CommentAuthorId}" title="View #{DisplayName}&#039;s Page" target="_blank"><em>#{DisplayName}</em></a> wrote:</strong>Posted #{PostedAtTime}</span><span class="r blocked">This comment has been removed by the moderator.</span></div></div>');
$S.setVal("tpl_cmtAbuseReport",'<a href="#" title="Close" id="cmt-abusereport-close" onclick="CBC.APP.PLUCK.Comments.closeAbuse();return false;"><img src="/includes/objects/pluck/gfx/close_sml.gif" alt="Close"/></a><h3>Report Abuse</h3><label>Report article as: (Required)</label><select name="cmt-abusereport-type" id="cmt-abusereport-type"><option value=""/><option value="Obscenity or vulgarity">Obscenity/vulgarity</option><option value="Hate speech">Hate speech</option><option value="Personal attack">Personal attack</option><option value="Advertising or Spam">Advertising/Spam</option><option value="Copyright or Plagiarism">Copyright/Plagiarism</option><option value="Other">Other</option></select><label>Comment: (Optional)</label><textarea name="cmt-abusereport-comment" id="cmt-abusereport-comment"></textarea><div class="clearfix"><input type="submit" id="cmt-abusereport-submit" name="cmt-abusereport-submit" value="Report" /><span id="cmt-abusereport-statusbox">Please select a report article.</span></div>');
//post status box messages
$S.setVal("cmt-post-statusbox-posted","Thank you for submitting a comment. Please note that comments are pre-moderated and may not appear immediately.");
$S.setVal("cmt-post-statusbox-maxchars","You have exceeded the maximum number of characters. Please type in a comment that is less than "+$S.getVal("maxCmtLength")+" characters.");
$S.setVal("cmt-post-statusbox-notloggedin",'You must be logged in to leave a comment. <a href="/sso/SSOAuthenticationDomain.ashx?mode=Login&amp;redirecturl='+document.location.href+'#socialcomments-submit">Log in</a> | <a href="/membercentre/SignUp.aspx" target="_blank">Sign up</a>');