var VM=VM||{};VM.Poll={$form:null,category:"",init:function(){VM.$body.find(".poll-extra").val(this.getExtraData())},initInline:function(n){this.$form=$("#poll-inline").on("submit",this.onSubmit).on("click",".poll-inline-toggler",function(){VM.Poll.toggleResults(!0)});this.$form.find(".poll-extra").val(this.getExtraData());this.category=n;console.log(n);VM.Ajax.resetValidation(this.$form)},getExtraData:function(){var n={Resolution:""+screen.width+"X"+screen.height+""};return JSON.stringify(n)},onSubmit:function(n){if(n.preventDefault(),VM.Poll.$form.valid()){var t=VM.Poll.$form.find("#poll-inline-vote").addClass("loading").prop("disabled",!0);$.ajax("/polls/votecontent",{method:"POST",data:VM.Poll.$form.serialize()}).done(function(n){if(n.options){var t=0;$.each(n.options,function(){t+=this.votes});t===0&&(t=1);$.each(n.options,function(){var n=VM.Poll.$form.find("#option_"+this.id),i=(this.votes/t*100).toFixed(1)+"%";n.find(".poll-details-voteinfo").text(this.votes+" vote"+(this.votes!==1?"s":"")+" "+i);n.find(".poll-details-votes").css("width",i)});VM.Poll.toggleResults(!1);VM.Poll.$form.find("#poll-inline-revote").remove();VM.Poll.trackEvent("Vote")}}).fail(function(){alert("There was a problem voting.")}).always(function(){t.removeClass("loading").prop("disabled",!1)})}},toggleResults:function(n){var t=VM.Poll.$form.find(".poll-inline-toggle").toggleClass("hidden");VM.Poll.$form.find(".poll-details-votes").css("animation","progress 600ms");n&&t.first().hasClass("hidden")&&VM.Poll.trackEvent("View Results")},trackEvent:function(n){var t={};t.eventCategory="In-Story Poll";t.eventAction=n;t.eventLabel=this.category;VM.Track.trackEvent(t)}};VM.Reactions={$form:null,$viewResults:null,viewResultsText:"",$buttons:null,canReact:!1,shownRelated:!1,init:function(){var n=this;this.$form=$("#reactions");this.$form.length&&(this.$viewResults=this.$form.find(".react-view").removeClass("hidden").on("click",this.onShowReactions),this.viewResultsText=this.$viewResults.text(),this.$buttons=this.$form.find(".bt-react").prop("disabled",!1).on("click",this.onReact),VM.Storage.hasStorage()&&$.ajax(this.$form.data("af"),{method:"POST"}).done(function(t){n.$form.append(t);n.activate()}))},activate:function(){var n=localStorage.getItem(this.getStorageKey());n?this.$buttons.addClass("reacted").filter("[value='"+n+"']").append('<div class="theme-colour">(yours)<\/div>'):this.canReact=!0},onReact:function(n){if(n.preventDefault(),VM.Reactions.canReact){var i=$(this).addClass("loading").prop("disabled",!0),t=i.attr("value");$.ajax(VM.Reactions.$form.attr("action")+"&subtype="+t,{method:"POST",data:VM.Reactions.$form.serialize()}).done(function(n){VM.Reactions.showReactions(n.Reactions,!1);switch(n.Result){case 0:localStorage.setItem(VM.Reactions.getStorageKey(),t);VM.Reactions.trackReaction(t);VM.Reactions.canReact=!1;break;case 1:VM.Reactions.errorMessage("There was a problem adding your reaction.");break;case 2:VM.Reactions.canReact=!1;VM.Reactions.errorMessage("It looks like you've already added your reaction.");break;case 3:VM.Reactions.canReact=!1;VM.Reactions.errorMessage("You've already added your reaction.")}VM.Reactions.showRelated(t)}).fail(function(){alert("There was a problem adding your reaction.")}).always(function(){i.removeClass("loading").prop("disabled",!1)})}},getStorageKey:function(){return"VM_reaction_"+this.$form.data("id")},onShowReactions:function(n){n.preventDefault();$.ajax(VM.Reactions.$form.data("results"),{method:"GET"}).done(function(n){VM.Reactions.showReactions(n,!0)}).fail(function(){alert("Sorry, the results are currently unavailable.")})},showReactions:function(n,t){var i,r;if(n!==null){var u=0,e=0,f=null;for(i in n)n.hasOwnProperty(i)&&(r=n[i],t&&r>e&&(e=r,f=i),u+=r);this.$buttons.each(function(){var t=$(this),i=0,r=n[t.attr("value")];r&&u>0&&(i=r/u);t.find("b").text((i*100).toFixed(0)+"%");t.find(".theme-bg").css("opacity",i)});t&&f&&this.showRelated(f)}},showRelated:function(n){if(!this.shownRelated){var t=this;$.ajax(VM.Reactions.$form.data("items").replace("=0","="+n),{method:"GET"}).done(function(i){if(t.shownRelated=!0,i.length>50){var r=$('<div class="react-related"><h3 class="theme-colour">Here are other recent stories that make people feel '+n.toLowerCase()+":<\/h3>"+i+"<\/div>");r.find(".section-tr-bordered:last").removeClass("section-tr-bordered");t.$form.append(r);VM.setup()}}).fail(function(){})}},errorMessage:function(n){var t=this.$form.find(".alert-warning");t.length?t.text(n):this.$form.find(".nav-react").after('<p class="alert alert-warning">'+n+"<\/p>")},trackReaction:function(n){var t={};t.eventCategory="Mood";t.eventAction=n;t.eventLabel=this.$form.data("category");VM.Track.trackEvent(t)}};VM.Momentum={id:null,tag:null,shareCount:0,commentCount:0,counters:0,countersRendered:0,dataSent:!1,init:function(){var n=VM.$body.find(".details"),i=n.find(".sc-s").last(),t=n.find("#comments-count");this.id=n.data("id");this.tag=n.data("tag");t.length===0&&(t=n.find(".sc-c"));i.length&&(this.counters++,this.watchCount(i,i.closest(".sc"),this.setShareCount));t.length&&(this.counters++,this.watchCount(t,t.parent(),this.setCommentsCount))},setShareCount:function(n){VM.Momentum.shareCount=n},setCommentsCount:function(n){VM.Momentum.commentCount=n},watchCount:function(n,t,i){var r=this,u=0,f=window.setInterval(function(){u++;t.hasClass("rendered")&&(clearInterval(f),i(parseInt(n.text(),10)),r.countersRendered++,r.countersRendered===r.counters&&r.sendData());u===100&&clearInterval(f)},50)},sendData:function(n,t,i,r){if(!this.dataSent){this.dataSent=!0;var u=$(window).width()+"x"+$(window).height();$.ajax("/sendmomentum?id="+(n||this.id)+"&tag="+(t||this.tag)+"&shares="+(i||this.shareCount||0)+"&comments="+(r||this.commentCount||0)+"&viewport="+u,{method:"POST"})}}};$(function(){VM.Poll.init();VM.Reactions.init();VM.Momentum.init()});VM=VM||{};VM.Comments={isAuthenticated:!1,loginUrl:"/account/login?ReturnUrl=",registerUrl:"/account/register?ReturnUrl=",$loader:null,$comments:null,$comment:null,maxCommentChars:0,$charsLeft:null,$form:null,$description:null,$descriptionSubmitArea:null,$perspectiveResultArea:null,$sort:null,$sorts:null,sort:null,startingSort:null,count:0,$count:null,$parentId:null,$alert:null,$popup:null,onFormLoaded:function(){if(VM.Comments.init(),window.location.search){var n=window.location.search.substring(1).split("=");n.length===2&&n[0]==="target"&&VM.scrollTo($("#"+n[1]))}},preinit:function(){var n=this,i=encodeURIComponent(window.location.pathname),t;this.loginUrl+=i;this.registerUrl+=i;this.$loader=$("#comments-loader");this.$sorts=$("#comments-sorts").on("click","a",this.onSort);this.$count=$("#comments-count");t=$("#comments-show").click(function(){n.load(t,n.$loader.data("endpoint"),null,function(i){n.$loader.html(i);n.init();t.remove()})});t.length&&$.getJSON(t.data("count-endpoint"),function(t){t&&(n.count=t.count,n.$count.text(n.count).removeClass("hidden").parent().addClass("rendered"))})},init:function(){this.$sort=$("#comments-sort").click(this.onSortToggle);this.sort=this.$sort.data("sort");this.startingSort=this.sort;this.$comments=$("#comments").on("click",".avatar-view",this.onProfileSummary).on("click",".comment-un",this.onProfileLinkClick).on("click",".comment-vote",this.onVote).on("click",".comment-replies",this.onGetReplies).on("click",".comments-more",this.onLoadComments).on("click",".comment-reply",this.onReply).on("click",".comment-report",this.onReport).on("click",".comment-edit",this.onEdit).on("click",".comment-pin",this.onPin).on("click",".comment-unpin",this.onUnpin).on("click",".comment-delete",this.onDelete);this.$form=$("#comment-form").on("click",".comment-cancel",this.onReplyCancel).submit(this.onSubmit).on("click",".comment-perspective-edit",this.onPerspectiveEdit).on("click",".comment-perspective-post",this.onPerspectivePost);$("#comments-post").removeClass("hidden").click(this.onComment);$("#comments-disclaimer").removeClass("hidden");this.$description=this.$form.find(".comment-form-desc").on("keyup paste",this.onDescriptionChange);this.maxCommentChars=parseInt(this.$description.data("val-length-max"),10);this.$charsLeft=this.$form.find(".comment-desc-left").removeClass("hidden").find("span").text(this.maxCommentChars);this.$descriptionSubmitArea=this.$form.find(".comment-submit-area");this.$perspectiveResultArea=this.$form.find(".comment-perspective");$(document).click(VM.Comments.onDocClick);this.afterCompleteLoad();this.afterLoad(this.$comments);$(window).click(this.closeAvatarSummary)},afterCompleteLoad:function(){this.isAuthenticated=this.$comments.data("auth");this.count=parseInt(this.$comments.data("count"),10);this.$count.text(this.count).removeClass("hidden").parent().addClass("rendered");this.count>3&&this.$sort.removeClass("hidden");this.checkAuthenticated(this.$form,"comment","comment-form");VM.Ajax.resetValidation(this.$form)},afterLoad:function(n){if(n&&n.length>0){var t=VM.Comments;n.find(".timeago").timeago();existingCount=0;count=0;n.hasClass("comment")?(existingCount=n.find(".comment").length,count=parseInt(n.data("replies"),10)):(existingCount=n.find(">.comment").length,count=t.count);existingCount<count&&n.find(".comments-more").removeClass("hidden")}},checkAuthenticated:function(n,t,i){if(this.isAuthenticated)return!0;var r=n[0].id==="comment-form",f=r?n.empty():n.closest(".comment"),u=encodeURIComponent("?target="+(i||"comments"));return this.$alert&&this.$alert.remove(),this.$alert=$('<p class="alert alert-warning">You must be signed in to '+t+'. Please <a href="'+this.loginUrl+u+'" class="alert-link">sign in<\/a> or <a href="'+this.registerUrl+u+'" class="alert-link">register<\/a>.<\/p>').appendTo(f),r?this.$form.removeClass("hidden").html(this.$alert.clone()):this.$form.addClass("hidden"),!1},onGetReplies:function(){var n=$(this).closest(".comment"),t=n.find(".comment-child"),i,r;if(t.length){t.remove();return}i=$(this);r=VM.Comments.$comments.data("endpoint").replace("Sort="+VM.Comments.startingSort,"Sort="+VM.Comments.sort)+"&ParentId="+n.data("id")+"&Count="+n.data("replies");VM.Comments.load(i,r,null,function(t){t='<div class="comment-child">'+t+"<\/div>";n.append(t);VM.Comments.afterLoad(n)})},onSortToggle:function(){VM.Comments.$sorts.toggleClass("hidden")},onSort:function(n){var t,i;n&&n.preventDefault();t=VM.Comments;t.sort=$(this).data("sort");$(this).addClass("sort-active").siblings().removeClass("sort-active");i=VM.Comments.$loader.data("endpoint").replace("Sort="+VM.Comments.startingSort,"Sort="+VM.Comments.sort);t.load(VM.Comments.$sort,i,null,function(n){var i=$(n).filter("#comments");t.$comments.html(i.html());t.afterCompleteLoad();t.afterLoad(VM.Comments.$comments)})},onDocClick:function(n){n.target.id!=="comments-sort"&&n.target.id!=="comments-sort-arrow"&&VM.Comments.$sorts.addClass("hidden")},onSubmit:function(n){n.preventDefault();var t=VM.Comments,i=t.$form.find(".comment-form-type").val();i==="Comment"?t.checkPerspective(VM.Comments.$description.val(),function(n){t.showPerspectiveMessage(n)||t.doSubmit()}):t.doSubmit()},doSubmit:function(){var n=VM.Comments;if(n.$form.valid()){var t=n.$form.find(".comment-submit"),i=n.$form.attr("action"),r=n.$form.serialize();VM.Comments.load(t,i,r,function(i){var y=n.$form.find(".comment-form-parent"),p=n.$form.find(".comment-form-type").val(),r,s,h,v;if(p==="Report")n.onReplyCancel.call(t),n.$comment.find(".comment-report").text("Reported").removeClass("comment-report").removeClass("btn-default").addClass("btn-warning"),n.$comment=null;else{VM.Track.onGaClick.call(t);var c=y.val(),e=n.getModerationMessage(i),o=e.length>0,l="",f="",u,a="<p>"+n.$description.val().replace(/(?:\r\n|\r|\n)/g,"<br>")+"<\/p>";l=i.avatar?'<a class="avatar-current avatar-sm avatar" href="/account" title="Change your photo"><img alt="'+i.username+'" class="avatar-img" src="'+i.avatar+';w=45;h=45;mode=crop"><\/a>':'<a class="theme-bg avatar-current avatar-sm avatar" href="/account" title="Add your photo">'+i.initials+"<\/a>";f='<div id="c_'+i.id+'" class="comment clearfix" data-id="'+i.id+'" data-replies="0">'+l+'<div class="comment-body"><div class="thread-date"><b class="theme-colour">'+i.username+'<\/b> Just now<\/div><div class="comment-text">'+a+e+'<\/div><div class="comment-actions"><form action="/comments/delete/'+i.id+'" class="pull-right" method="post">'+i.af+'<button type="button" class="btn btn-default btn-ns btn-xs comment-delete" title="Delete your comment"><i class="ic ic-delete"><\/i><\/button><\/form><button type="button" class="btn btn-default btn-ns btn-xs pull-right comment-edit" title="Edit your comment"><i class="ic ic-edit"><\/i><\/button><\/div><\/div><\/div>';c?(r=$("#c_"+c),i.edited?(r.find(">.comment-body .comment-text").html(a).append(e),u=r):(s=r.find(".comment-child"),s.length?(u=n.addReply(f,s,!0),o||(h=r.data("replies")+1,v=r.find(".comment-replies"),r.data("replies",h),v.html(h+' Replies <i class="caret"><\/i>'))):u=$('<div class="comment-child">'+f+"<\/div>").appendTo(r)),n.onReplyCancel.call(t),n.$comment=null):(u=n.addReply(f,n.$comments,!1),o||n.$count.text(parseInt(n.$count.text(),10)+1));o&&u.find(">.comment-body .comment-actions").remove();VM.scrollTo(u)}n.$description.val("");n.$charsLeft.text(n.maxCommentChars);n.$form.find(".comment-form-score").val(0)})}},getModerationMessage:function(n){if(n.status==="Moderation"){var t="";switch(n.moderation){case"ModerateUser":t="Your comment has been flagged for moderation";break;case"ModerateNewUser":t="All comments posted by new accounts are flagged for moderation";break;case"ModerateContent":t="All comments related to this story are currently being moderated";break;case"ModerateSite":t="All comments are currently being moderated";break;case"ModerateComment":t="Your comment has been flagged for moderation based on content contained within"}return'<p class="alert alert-warning">'+t+". You will receive an email notification if your comment is not approved.<\/p>"}return""},addReply:function(n,t,i){return this.sort==="Oldest"||i?$(n).appendTo(t):$(n).prependTo(t)},onLoadComments:function(){var n=$(this),i,t=n.data("parent"),u=t?"Oldest":VM.Comments.sort,r=VM.Comments.$comments.data("endpoint").replace("Sort="+VM.Comments.startingSort,"Sort="+u)+"&lastId="+n.prev().data("id")+"&ParentId="+t+"&Count=";VM.Track.onGaClick.call(n);t?(i=n.closest(".comment"),r+=i.data("replies")):r+=VM.Comments.count;VM.Comments.load(n,r,null,function(r){n.replaceWith(r);t?VM.Comments.afterLoad(i):VM.Comments.afterLoad(VM.Comments.$comments)})},load:function(n,t,i,r){n.addClass("loading").prop("disabled",!0);$.ajax(t,{method:i===null?"GET":"POST",data:i}).done(r).fail(function(n,t,i){alert(n.responseText||i)}).always(function(){n.removeClass("loading").prop("disabled",!1)})},onComment:function(){VM.Comments.checkAuthenticated(VM.Comments.$form,"comment","comment-form");VM.scrollTo(VM.Comments.$form)},onReply:function(){VM.Comments.checkAuthenticated($(this),"reply")&&VM.Comments.changeState(this,"Comment","Add your reply","Post Reply")},onReport:function(){VM.Comments.checkAuthenticated($(this),"report this comment")&&VM.Comments.changeState(this,"Report","Please explain why you're reporting this comment","Report")},onEdit:function(){VM.Comments.changeState(this,"Comment","Update your comment","Update");var n=$(this).closest(".comment"),t=n.find(".comment-text").html().replace(/<\/p><p>/g,"\n\n").replace(/<p>/g,"").replace(/<\/p>/g,"").replace(/<br>/g,"\n");VM.Comments.$description.val(t);VM.Comments.$form.find(".comment-form-editid").val(n.data("id"))},onPin:function(){var n=$(this);VM.Comments.pin(n,!0,function(){n.addClass("hidden").next().removeClass("hidden")})},onUnpin:function(){var n=$(this);VM.Comments.pin(n,!1,function(){n.addClass("hidden").prev().removeClass("hidden")})},pin:function(n,t,i){n.addClass("loading").prop("disabled",!0);$.ajax(n.parent().data("endpoint"),{method:"POST",data:"pin="+t}).done(function(){i()}).fail(function(n,t,i){alert(n.responseText||i)}).always(function(){n.removeClass("loading").prop("disabled",!1)})},onDelete:function(){if(confirm("Are you sure you want to delete this comment?")){var n=VM.Comments,i=$(this),t=i.closest("form"),r=t.attr("action"),u=t.serialize();VM.Comments.load(i,r,u,function(){var f=t.closest(".comment"),r=f.parent();if(r.hasClass("comment-child")){var u=r.parent(),i=u.data("replies")-1,e=u.find(".comment-replies");u.data("replies",i);i===0?(e.remove(),r.remove()):e.html(i+(i===1?" Reply ":" Replies ")+'<i class="caret"><\/i>')}else n.$count.text(parseInt(n.$count.text(),10)-1),n.count--;f.remove()})}},onReplyCancel:function(){VM.Comments.changeState(null,"Comment","Add your comment","Post Comment")},changeState:function(n,t,i,r){var u;n!==null?(this.$comment=$(n).closest(".comment").addClass("comment-replying"),$(n).hasClass("comment-edit")?this.$form.insertAfter(this.$comment.find(">.comment-body .comment-actions")):this.$comment.append(this.$form),u=this.$comment.data("id")):(this.$comment.removeClass("comment-replying"),this.$form.insertAfter(this.$comments),u=null);this.$description.val("").attr("placeholder",i);this.$form.find(".comment-form-editid").val("");this.$form.find("label.sr-only").text(i);this.$form.find(".comment-submit").text(r);this.$form.find(".comment-cancel").toggleClass("hidden",n===null);this.$form.find(".comment-form-parent").val(u);this.$form.find(".comment-form-type").val(t);n!==null&&this.$description.focus()},onVote:function(){var n=$(this);if(VM.Comments.checkAuthenticated(n,"vote")){var t=n.closest("form"),i=t.attr("action")+"&type="+n.val(),r=t.serialize();VM.Comments.load(n,i,r,function(i){if(i)t.find(".comment-vote[value='Upvote'] span").text(i.upvotes),t.find(".comment-vote[value='Downvote'] span").text(i.downvotes),VM.Track.onGaClick.call(n);else{var r=JSON.parse(xhr.getResponseHeader("X-Responded-JSON"));r&&r.status===401&&alert("You need to sign in.")}})}},onDescriptionChange:function(){VM.Comments.$charsLeft[0].innerText=VM.Comments.maxCommentChars-this.value.length},checkPerspective:function(n,t){var i={comment:{text:n},languages:["en"],requestedAttributes:{TOXICITY:{},OBSCENE:{}}};$.ajax("https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=AIzaSyByrN2npmkT86GzSFVyv-gsB11JqE8vKak",{method:"POST",dataType:"json",contentType:!1,data:JSON.stringify(i)}).done(function(n){var i={toxicity:n.attributeScores.TOXICITY.summaryScore.value,obscenity:n.attributeScores.OBSCENE.summaryScore.value};t(i)}).fail(function(n,i,r){t({error:r})})},showPerspectiveMessage:function(n){var i=this.$perspectiveResultArea.find(".message").empty(),t=!1;return VM.Comments.$form.find(".comment-form-score").val(n.toxicity),n.toxicity>=.75&&(t=!0,i.append('<p>Our filter has rejected your comment. We aim to provide a space for thoughtful discussion. Perhaps consider rewording and submitting again. Please remember our <a href="/community-guidelines">Community Guidelines<\/a> when commenting.<\/p>')),n.obscenity>=.75&&(t=!0,i.append('<p>It appears that your comment contains one or more obscene words or phrases, which goes against our <a href="/community-guidelines">Community Guidelines<\/a>. You can modify your comment and resubmit it, or you can submit it for manual review by our news desk.<\/p>')),t&&(this.$perspectiveResultArea.removeClass("hidden"),this.$descriptionSubmitArea.addClass("hidden"),this.$description.prop("disabled",!0)),t},onPerspectivePost:function(){VM.Comments.onPerspectiveEdit();VM.Comments.doSubmit()},onPerspectiveEdit:function(){VM.Comments.$perspectiveResultArea.addClass("hidden");VM.Comments.$descriptionSubmitArea.removeClass("hidden");VM.Comments.$description.prop("disabled",!1);VM.scrollTo(VM.Comments.$description)},onProfileSummary:function(n){n.preventDefault();var t=$(this),i=!1;VM.Comments.$popup&&(i=VM.Comments.$popup.find(".avatar").attr("href")===t.attr("href"),VM.Comments.$popup.remove(),VM.Comments.$popup=null);i||(VM.Comments.$popup=$('<div class="popup popup-bubble avatar-popup" style="top:'+(t.offset().top+58)+"px;left: "+t.offset().left+'px"><\/div>').load(t.attr("href")+"/summary"),$("body").append(VM.Comments.$popup))},onProfileLinkClick:function(n){$(this).hasClass("comment-un-current")||(n.preventDefault(),$(this).closest(".comment-body").prev().click())},closeAvatarSummary:function(n){if(VM.Comments.$popup){var t=$(n.target);t.hasClass("avatar-img")||t.hasClass("avatar")||t.hasClass("comment-un")||(VM.Comments.$popup.remove(),VM.Comments.$popup=null)}}};$(function(){VM.Comments.preinit()})