var tbState,tbCallbacks,tbForms,tbActions,tbHelpers;
function stateInit(){
var baseURL="http://api.kickapps.com/rest/";
tbHelpers={
formatDate:function(d) {
var t = new Date(d),MONTH = ['January','February','March','April','May','June','July','August','September','October','November','December'];
return MONTH[t.getMonth()] + " " + t.getDate() + ', ' + t.getFullYear();
},
formatTime:function(d){
var getHour=function(h){return h>12?h-12:h==0?12:h;}
var getMins=function(m){return m>10?m.toString():"0"+m.toString();}
var t=new Date(d),hour=t.getHours(),mins=t.getMinutes(),ampm=hour>=12?"pm":"am";
return getHour(hour).toString()+":"+getMins(mins)+ampm;
},
decryptor:function(encryptedStr) {
if (!encryptedStr) return "";
var x= "",resultStr = "";
encryptedStr = encryptedStr.reverse();
for (i=0;i < encryptedStr.length; i++){
x=encryptedStr.substr(i,1);
resultStr = resultStr + String.fromCharCode( x.charCodeAt(0) - 1 );
}
return resultStr;
},
getAuthToken:function() {
return this.decryptor(zdjs.readCookie(tbState.kCk,'at'));
},
getNewResultsCount:function(data){
if(parseInt($('#w_talkbackCount').text())>tbState.currCount){tbState.currCount=parseInt($('#w_talkbackCount').text());}
var currMax = tbState.maxId, x=0,currVal;
for(var i = 0; i < data.length; ++i){
currVal=parseInt(data[i].messageId);
if(currVal>currMax){++x;}else{break;}
}
return tbState.currCount+=x;
},
scrubComment:function(commentText){
var re = /(
)/gm;
commentText = commentText.replace(re, "");
re = /(<|>|&(?!(amp|gt|lt);))/ig;
commentText = commentText.replace(re, function($1){return arguments[0]=="<"?"<":arguments[0]=="&"?"&":">";});
re = /\n+/gm;
commentText = commentText.replace(re, "
");
return commentText;
},
jsonpRequest:function(url,data,callback){
try{
$.ajax({
url: url,
data: data,
dataType: 'jsonp',
type: 'GET',
success: callback
});
}catch(e){ }
},
parseLongText:function(ct){
var r1=/\S{35,}/g;
var mm=ct.match(r1),lt=false,t="",u="";
if(mm){
lt=true;
for(var i=0;i
";
}
}
if(lt){tbForms.addErrorMessage("
Some words exceed 35 characters in length:
"+t+"Please edit and resubmit.","#addCommentForm");$('#addCommentSubmit').show("slow");}
else if(u&&false){//skipped for now 09.03.00
var ua=u.split(" ",1),uri="";
tbState.actionParams=ua[0];
tbHelpers.jsonpRequest("http://api.tr.im/api/trim_url.json",{url:ua[0]}, tbCallbacks.checkTrimResponse );
}else{ //we can go ahead and submit
tbState.currentAction="postComment";
tbState.actionParams=ct;
tbActions.postComment();
}
},
getLoginAction:function(){
var cz=zdjs.isCookie(tbState.zCk),ck=zdjs.isCookie(tbState.kCk),authToken = '';
if (ck&&cz) {authToken=this.getAuthToken();
return authToken.length>0?null:"getAuthToken";}
else if(!cz){return "login";}
else{return "kaLogin";}
},
actionProxy:function(){//called from login callback for stateful handling
if(tbState.currentAction=="postComment"){tbState.actionParams=$("#newComment").val();//tbActions.postComment();
tbActions.processTBForm();}
else if(tbState.currentAction=="showReportThis"){tbForms.showReportThis(tbState.actionParams);}
},
reportClicked:function(id){
tbState.currentAction="showReportThis";
tbState.actionParams=id;
var loginAction=tbHelpers.getLoginAction();
if (loginAction==null) {tbForms.showReportThis(tbState.actionParams);}
else if(loginAction=="login") {
tbForms.addErrorMessage("You must be logged in to report a comment.","#addCommentForm");
tbForms.displaySignIn();}
else{zdjs.login("do="+loginAction,tbCallbacks.checkLoginResponse);}
},
scrollToTop:function(elementId){window.scrollTo(0, $(elementId).offset().top);}
}
var as=tbHelpers.decryptor($("#var4").text());
tbState={
articleId:$("#var1").text(),
articleUrl:$("#var2").text(),
sortOldestFirst:$("#var6").text(),
tk:tbHelpers.decryptor($("#var3").text()),
as:as,
talkbacksPerPage:parseInt($("#var5").text()),
currCount:parseInt($("#var7").text()),
maxTalkbackLength:2000,
zCk:"zm%5Fuser",
kCk:"zdkasso",
cPage:1,
rPage:1,
maxId:0,
zdu:"",
zdp:"",
urlEnd:"/"+as,
getURL:baseURL+"comments/"+as,
addURL:baseURL+"comment/add/emedia/",
flagURL:baseURL+"flagcomment/",
currentAction:null,
actionParams:null,
flaggedComments:[]
}
tbActions={
processTBForm:function(){
var ct=tbState.actionParams;
tbState.currentAction="parseLongText";
tbHelpers.parseLongText(ct);
//we need to parse any long text, identifying urls if present
//we need to process any long urls
//we need to scrub the comments
//finally we need to post the scrubbed comment to kickapps
},
getTalkback:function(requestedPage,scroll){
tbState.rPage = parseInt(requestedPage);
tbState.currentAction = "getComments";
tbHelpers.jsonpRequest(tbState.getURL,{t: tbState.tk,
url:tbState.articleUrl,
mediaType:'emedia',
mediaId:tbState.articleId,
pgNum:requestedPage,
totSize:tbState.currCount,
pgSize:tbState.talkbacksPerPage,
userId: 0,
sortOldestFirst:tbState.sortOldestFirst},tbCallbacks.checkRetrieveResponse);
if(scroll){tbHelpers.scrollToTop("#talkbackTop");}
return false;
},
postComment:function(){
var commentText = tbState.actionParams;
var sendURL = tbState.addURL+tbState.articleId+tbState.urlEnd;
var url = encodeURI(tbState.articleUrl),authToken = "";
tbState.actionParams=null;
authToken = tbHelpers.getAuthToken();
if(tbForms.commentValidate(commentText, "#addCommentForm",tbState.maxTalkbackLength)){
commentText=tbHelpers.scrubComment(commentText);
tbHelpers.jsonpRequest(sendURL,{t: authToken,
url:url,
comment:commentText},tbCallbacks.checkCommentResponse);
return false;
}
},
flagComment:function(id,o){
var txt=$("p#"+id+"text").text(),name=$("#"+id).parent().text();
var furl=tbState.flagURL+id+"/emedia/"+tbState.articleId+tbState.urlEnd;
var mediaName=$("h1.articleTitle").text(),t=tbHelpers.getAuthToken(),message=$("#reportMessage").val();
if (tbForms.commentValidate(message,"#reportCommentPopup",5000)){
tbHelpers.jsonpRequest(furl,{t: t,
commentedByusername:name,
commentText:txt,
mediaName: mediaName,
message:message},tbCallbacks.checkFlagResponse);
$(o).parent().remove();
$("#"+id+" > img[src$='button_report.gif']").remove();
$("#"+id).append("Thanks for your feedback.");
tbState.flaggedComments.push(id);
}
}
}
tbCallbacks={
checkCommentResponse:function(data){
if(data.status=="1" && data.error=="" &&data.comments.length>0) {
var page=/\bt\b/i.test(tbState.sortOldestFirst)?function(){return Math.ceil(++tbState.currCount/tbState.talkbacksPerPage);}():1;
tbActions.getTalkback(page,true);
tbState.rPage=page;
tbForms.resetForms();
}else{}
},
checkRetrieveResponse:function(data){
var count = parseInt(data.totSize);
if(data.status == '1' && data.error == '' &&data.results.length > 0) {
tbState.cPage=tbState.rPage;
tbForms.paintTalkbacks(data.results,count);
} else if(data.results.length==0&&count==0){}else{}
tbState.currentAction=null;
tbState.actionParams=null;
$('#addCommentSubmit').show("slow");
},
checkFlagResponse:function(data){},
checkTrimResponse:function(data){
alert(data.url);
alert(tbState.actionParams);
var ct = $("#newComment").val().replace(tbState.actionParams,data.url);
alert(ct);
//tbHelpers.parseLongText(ct);
},
checkLoginResponse:function(data){
$("#addCommentForm span.error").remove();
$("#tbSignInForm span.error").remove();
var m = /({.*})/.exec(data),errorMsg = '';
data = eval("(" + m[0] + ")");
if (data.response.status == "error") {
errorMsg = "Your login failed due to: " + data.response.message ;
tbForms.addErrorMessage(errorMsg,"#tbSignInForm");
}else if(data.response.status == "ka_error"){
errorMsg = "You are unable to post talkback at this time."
tbForms.addErrorMessage(errorMsg,"#addCommentForm");
}else {
tbForms.hideSignIn();
tbHelpers.actionProxy();
}
if(insertNavLinks){
$("#memberArea").empty();
insertNavLinks();
}
}
}
tbForms={
countChars:function(e){
var t=e.currentTarget,p=$("p.maxChar:first"),l=t.value.length,r=tbState.maxTalkbackLength,isChar=false,errorMsg="",code=e.keyCode?e.keyCode:e.which;
$("#addCommentForm span.error").remove();
switch(code){
case 8, 1:
if(l>0){r-=l;}break;
case 0:
r-=l+1;isChar=true;break;
default:
r-=l;
}
if(r>=0){p.text(r+" character"+(r>1?"s":"")+" remaining");}
else{
p.text("0 characters remaining");
errorMsg = 'Your comment is '+(r*-1)+' character'+(r*-1>1?'s':'')+' too long. Please remove some text.';
tbForms.addErrorMessage(errorMsg,"#addCommentForm");
}
},
maxLengthCheck:function(e){
var l=e.currentTarget.value.length,errorMsg = "";
$("#addCommentForm span.error").remove();
if(l>tbState.maxTalkbackLength){
errorMsg = "Your comment is "+(l-tbState.maxTalkbackLength)+" character"+(l-tbState.maxTalkbackLength>1?"s":"")+" too long. Please remove some text.";
tbForms.addErrorMessage(errorMsg,"#addCommentForm");
}
return true;
},
commentValidate:function(commentText, form, maxLen) {
var errorMsg = '';
$(form+" span.error").remove();
if (commentText.length == 0) {
errorMsg = 'Please enter your comment';
tbForms.addErrorMessage(errorMsg,"#addCommentForm");
return false;
}else if(commentText.length>maxLen){
errorMsg = 'Your comment exceeds '+maxLen+' characters. Please remove some text.';
tbForms.addErrorMessage(errorMsg,form);
return false;
}
return true;
},
displaySignIn:function() {
$("#talkbackSignIn").css("display", "block");
tbHelpers.scrollToTop("#w_addComment");
},
hideSignIn:function() {
$("#talkbackSignIn").css("display", "none");
},
resetForms:function(){
$("#newComment").val("");
$("#w_addComment > p.maxChar:first").text("( maximum 2000 Characters )");
$("input#tb_username").attr("value", "");
$("input#tb_password").attr("value");
tbForms.hideSignIn();
},
checkLoginFields:function() {
var errorMsg="";
$("#tbSignInForm span.error").remove();
tbState.zdu = $("input#tb_username").attr("value");
tbState.zdp = $("input#tb_password").attr("value");
if (tbState.zdu.length > 0 && tbState.zdp.length > 0){return true;}
if (tbState.zdu.length == 0 ) {errorMsg = "Username is required. ";}
if (tbState.zdp.length == 0 ) {errorMsg += "Password is required";}
this.addErrorMessage(errorMsg,"#tbSignInForm");
return false;
},
addErrorMessage:function(msg,loc){
$("").addClass("error").html(msg).appendTo(loc);
},
showReportThis:function(id){
tbState.actionParams=null;
var h=392,w=264,voffset=h/2,hoffset=w/2,winH=parseInt($(window).height()),winW=parseInt($("#wrapperPage").width()),left=winW/2-hoffset,top=winH/2-voffset;
var ele = '
To report an offensive comment that you believe violates the '+ 'PCMag.com Terms of Use, type your reason in the field below and click the Submit button.'+ '
' + tbHelpers.formatDate(data[i].createdAt)+' '+tbHelpers.formatTime(data[i].createdAt)+'
' + data[i].body + '
'; $('#articleTalkbacks').append(html); } }, paginateTalkbacks:function(totalPageLinks) { if(totalPageLinks>1){ var FIRSTPAGE=1,lastPage=totalPageLinks,before=3,after=3,ellipsis="...",separator="|",navSpacer="",seriesBegin=tbState.cPage-before,seriesEnd=tbState.cPage+after,firstPageLink="",lastPageLink="",seriesLink=""; if (seriesBegin < FIRSTPAGE) {seriesBegin = FIRSTPAGE + 1;} else if (seriesBegin == FIRSTPAGE){seriesBegin++;} if (seriesBegin == FIRSTPAGE + 1 ) {navSpacer = separator;} else {navSpacer = ellipsis;} if (tbState.cPage == FIRSTPAGE) {firstPageLink = '