🔥 Deduplicate some code
[Sone.git] / src / main / resources / static / javascript / sone.js
1 /* Sone JavaScript functions. */
2
3 function ajaxGet(url, data, successCallback, errorCallback) {
4         (function(url, data, successCallback, errorCallback) {
5                 $.ajax({"cache": false, "type": "GET", "url": url, "data": data, "dataType": "json", "success": function(data, textStatus) {
6                         ajaxSuccess();
7                         if (typeof successCallback != "undefined") {
8                                 successCallback(data, textStatus);
9                         }
10                 }, "error": function(xmlHttpRequest) {
11                         if (xmlHttpRequest.status === 403) {
12                                 notLoggedIn = true;
13                         }
14                         if (typeof errorCallback != "undefined") {
15                                 errorCallback();
16                         } else {
17                                 ajaxError();
18                         }
19                 }});
20         })(url, data, successCallback, errorCallback);
21 }
22
23 function registerInputTextareaSwap(inputElement, defaultText, inputFieldName, optional, dontUseTextarea) {
24         $(inputElement).each(function() {
25                 const textarea = $(dontUseTextarea ? "<input type=\"text\" name=\"" + inputFieldName + "\">" : "<textarea name=\"" + inputFieldName + "\"></textarea>").blur(function() {
26                         if ($(this).val() === "") {
27                                 $(this).hide();
28                                 const inputField = $(this).data("inputField");
29                                 inputField.show().removeAttr("disabled").addClass("default");
30                                 inputField.val(defaultText);
31                         }
32                 }).hide().data("inputField", $(this)).val($(this).val());
33                 $(this).data("textarea", textarea).after(textarea);
34                 (function(inputField, textarea) {
35                         inputField.focus(function() {
36                                 $(this).hide().prop("disabled", "disabled");
37                                 /* no, show(), â€śdisplay: block” is not what I need. */
38                                 textarea.prop("style", "display: inline").focus();
39                         });
40                         if (inputField.val() === "") {
41                                 inputField.addClass("default");
42                                 inputField.val(defaultText);
43                         } else {
44                                 inputField.hide().prop("disabled", "disabled");
45                                 textarea.show();
46                         }
47                         $(inputField.get(0).form).submit(function() {
48                                 inputField.prop("disabled", "disabled");
49                                 if (!optional && (textarea.val() === "")) {
50                                         inputField.removeAttr("disabled").focus();
51                                         return false;
52                                 }
53                         });
54                 })($(this), textarea);
55         });
56 }
57
58 /**
59  * Adds a â€ścomment” link to all status lines contained in the given element.
60  *
61  * @param postId
62  *            The ID of the post
63  * @param element
64  *            The element to add a â€ścomment” link to
65  */
66 function addCommentLink(postId, author, element, insertAfterThisElement) {
67         if (($(element).find(".show-reply-form").length > 0) || (getPostElement(element).find(".create-reply").length === 0)) {
68                 return;
69         }
70         (function(postId, author, insertAfterThisElement) {
71                 const separator = $("<span> Â· </span>").addClass("separator");
72                 getTranslation("WebInterface.Button.Comment", function(text) {
73                         const commentElement = $("<div><span>" + text + "</span></div>").addClass("show-reply-form").click(function() {
74                                 const replyElement = sone.find(".post#post-" + postId + " .create-reply");
75                                 replyElement.removeClass("hidden");
76                                 replyElement.removeClass("light");
77                                 (function(replyElement) {
78                                         replyElement.find(":input.reply-input").blur(function() {
79                                                 if ($(this).hasClass("default")) {
80                                                         replyElement.addClass("light");
81                                                 }
82                                         }).focus(function() {
83                                                 replyElement.removeClass("light");
84                                         });
85                                 })(replyElement);
86                                 const textArea = replyElement.find(":input.reply-input").focus().data("textarea");
87                                 if (author !== getCurrentSoneId()) {
88                                         textArea.val(textArea.val() + "@sone://" + author + " ");
89                                 }
90                         });
91                         $(insertAfterThisElement).after(commentElement.clone(true));
92                         $(insertAfterThisElement).after(separator);
93                 });
94         })(postId, author, insertAfterThisElement);
95 }
96
97 const translations = {};
98
99 /**
100  * Retrieves the translation for the given key and calls the callback function.
101  * The callback function takes a single parameter, the translated string.
102  *
103  * @param key
104  *            The key of the translation string
105  * @param callback
106  *            The callback function
107  */
108 function getTranslation(key, callback) {
109         if (key in translations) {
110                 callback(translations[key]);
111                 return;
112         }
113         ajaxGet("getTranslation.ajax", {"key": key}, function(data) {
114                 if ((data != null) && data.success) {
115                         translations[key] = data.value;
116                         callback(data.value);
117                 }
118         });
119 }
120
121 /**
122  * Filters the given Sone ID, replacing all â€ś~” characters by an underscore.
123  *
124  * @param soneId
125  *            The Sone ID to filter
126  * @returns The filtered Sone ID
127  */
128 function filterSoneId(soneId) {
129         return soneId.replace(/[^a-zA-Z0-9-]/g, "_");
130 }
131
132 /**
133  * Updates the status of the given Sone.
134  *
135  * @param soneId
136  *            The ID of the Sone to update
137  * @param status
138  *            The status of the Sone (“idle”, â€śunknown”, â€śinserting”,
139  *            â€śdownloading”)
140  * @param modified
141  *            Whether the Sone is modified
142  * @param locked
143  *            Whether the Sone is locked
144  * @param lastUpdated
145  *            The date and time of the last update (formatted for display)
146  */
147 function updateSoneStatus(soneId, name, status, modified, locked, lastUpdated, lastUpdatedText) {
148         const updateSone = sone.find(".sone." + filterSoneId(soneId));
149         updateSone.toggleClass("unknown", status === "unknown").
150                 toggleClass("idle", status === "idle").
151                 toggleClass("inserting", status === "inserting").
152                 toggleClass("downloading", status === "downloading").
153                 toggleClass("modified", modified);
154         updateSone.find(".lock").toggleClass("hidden", locked);
155         updateSone.find(".unlock").toggleClass("hidden", !locked);
156         if (lastUpdated != null) {
157                 updateSone.find(".last-update span.time").prop("title", lastUpdated).text(lastUpdatedText);
158         } else {
159                 getTranslation("View.Sone.Text.UnknownDate", function(unknown) {
160                         updateSone.find(".last-update span.time").text(unknown);
161                 });
162         }
163         updateSone.find(".profile-link a").text(name);
164 }
165
166 /**
167  * Enhances a â€śdelete” button so that the confirmation is done on the same page.
168  *
169  * @param button
170  *            The button element
171  * @param text
172  *            The text to show on the button
173  * @param deleteCallback
174  *            The callback that actually deletes something
175  */
176 function enhanceDeleteButton(button, text, deleteCallback) {
177         (function(button) {
178                 const newButton = $("<button></button>").addClass("confirm").hide().text(text).click(function() {
179                         $(this).fadeOut("slow");
180                         deleteCallback();
181                         return false;
182                 }).insertAfter(button);
183                 (function(button, newButton) {
184                         button.click(function() {
185                                 button.fadeOut("slow", function() {
186                                         newButton.fadeIn("slow");
187                                         $(document).one("click", function() {
188                                                 if (this !== newButton.get(0)) {
189                                                         newButton.fadeOut(function() {
190                                                                 button.fadeIn();
191                                                         });
192                                                 }
193                                         });
194                                 });
195                                 return false;
196                         });
197                 })(button, newButton);
198         })($(button));
199 }
200
201 /**
202  * Enhances a post’s â€śdelete” button.
203  *
204  * @param button
205  *            The button element
206  * @param postId
207  *            The ID of the post to delete
208  * @param text
209  *            The text to replace the button with
210  */
211 function enhanceDeletePostButton(button, postId, text) {
212         enhanceDeleteButton(button, text, function() {
213                 ajaxGet("deletePost.ajax", { "post": postId, "formPassword": getFormPassword() }, function(data) {
214                         if (data == null) {
215                                 return;
216                         }
217                         if (data.success) {
218                                 sone.find(".post#post-" + postId).slideUp();
219                         } else if (data.error === "invalid-post-id") {
220                                 /* pretend the post is already gone. */
221                                 getPost(postId).slideUp();
222                         } else if (data.error === "auth-required") {
223                                 alert("You need to be logged in.");
224                         } else if (data.error === "not-authorized") {
225                                 alert("You are not allowed to delete this post.");
226                         }
227                 }, function() {
228                         /* ignore error. */
229                 });
230         });
231 }
232
233 /**
234  * Enhances a reply’s â€śdelete” button.
235  *
236  * @param button
237  *            The button element
238  * @param replyId
239  *            The ID of the reply to delete
240  * @param text
241  *            The text to replace the button with
242  */
243 function enhanceDeleteReplyButton(button, replyId, text) {
244         enhanceDeleteButton(button, text, function() {
245                 ajaxGet("deleteReply.ajax", { "reply": replyId, "formPassword": sone.find("#formPassword").text() }, function(data) {
246                         if (data == null) {
247                                 return;
248                         }
249                         if (data.success) {
250                                 sone.find(".reply#reply-" + replyId).slideUp();
251                         } else if (data.error === "invalid-reply-id") {
252                                 /* pretend the reply is already gone. */
253                                 getReply(replyId).slideUp();
254                         } else if (data.error === "auth-required") {
255                                 alert("You need to be logged in.");
256                         } else if (data.error === "not-authorized") {
257                                 alert("You are not allowed to delete this reply.");
258                         }
259                 }, function() {
260                         /* ignore error. */
261                 });
262         });
263 }
264
265 function getFormPassword() {
266         return sone.find("#formPassword").text();
267 }
268
269 /**
270  * Returns the element of the Sone with the given ID.
271  *
272  * @param soneId
273  *            The ID of the Sone
274  * @returns All Sone elements with the given ID
275  */
276 function getSone(soneId) {
277         return sone.find(".sone").filter(function() {
278                 return $(".id", this).text() === soneId;
279         });
280 }
281
282 function getSoneElement(element) {
283         return $(element).closest(".sone");
284 }
285
286 /**
287  * Returns the ID of the sone of the context menu that contains the given
288  * element.
289  *
290  * @param element
291  *            The element within a context menu to get the Sone ID for
292  * @return The Sone ID
293  */
294 function getMenuSone(element) {
295         return $(element).closest(".sone-menu").find(".sone-menu-id").text();
296 }
297
298 /**
299  * Generates a list of Sones by concatening the names of the given sones with a
300  * comma.
301  *
302  * @param sones
303  *            The sones to format
304  * @returns {String} The created string
305  */
306 function generateSoneList(sones) {
307         return sones.map(sone => sone.name).join(", ")
308 }
309
310 /**
311  * Returns the ID of the Sone that this element belongs to.
312  *
313  * @param element
314  *            The element to locate the matching Sone ID for
315  * @returns The ID of the Sone, or undefined
316  */
317 function getSoneId(element) {
318         return getSoneElement(element).find(".id").text();
319 }
320
321 /**
322  * Returns the element of the post with the given ID.
323  *
324  * @param postId
325  *            The ID of the post
326  * @returns The element of the post
327  */
328 function getPost(postId) {
329         return sone.find(".post#post-" + postId);
330 }
331
332 function getPostElement(element) {
333         return $(element).closest(".post");
334 }
335
336 function getPostId(element) {
337         return getPostElement(element).prop("id").substr(5);
338 }
339
340 function getPostTime(element) {
341         return getPostElement(element).find(".post-time").text();
342 }
343
344 /**
345  * Returns the author of the post the given element belongs to.
346  *
347  * @param element
348  *            The element whose post to get the author for
349  * @returns The ID of the authoring Sone
350  */
351 function getPostAuthor(element) {
352         return getPostElement(element).find(".post-author").text();
353 }
354
355 /**
356  * Returns the element of the reply with the given ID.
357  *
358  * @param replyId
359  *            The ID of the reply
360  * @returns The element of the reply
361  */
362 function getReply(replyId) {
363         return sone.find(".reply#reply-" + replyId);
364 }
365
366 function getReplyElement(element) {
367         return $(element).closest(".reply");
368 }
369
370 function getReplyId(element) {
371         return getReplyElement(element).prop("id").substr(6);
372 }
373
374 function getReplyTime(element) {
375         return getReplyElement(element).find(".reply-time").text();
376 }
377
378 /**
379  * Returns the author of the reply the given element belongs to.
380  *
381  * @param element
382  *            The element whose reply to get the author for
383  * @returns The ID of the authoring Sone
384  */
385 function getReplyAuthor(element) {
386         return getReplyElement(element).find(".reply-author").text();
387 }
388
389 /**
390  * Returns the notification with the given ID.
391  *
392  * @param notificationId
393  *            The ID of the notification
394  * @returns The notification element
395  */
396 function getNotification(notificationId) {
397         return sone.find("#notification-area .notification#" + notificationId);
398 }
399
400 /**
401  * Returns the notification element closest to the given element.
402  *
403  * @param element
404  *            The element to get the closest notification of
405  * @return The closest notification element
406  */
407 function getNotificationElement(element) {
408         return $(element).closest(".notification");
409 }
410
411 /**
412  * Returns the ID of the notification element.
413  *
414  * @param notificationElement
415  *            The notification element
416  * @returns The ID of the notification
417  */
418 function getNotificationId(notificationElement) {
419         return $(notificationElement).prop("id");
420 }
421
422 /**
423  * Returns the time the notification was last updated.
424  *
425  * @param notificationElement
426  *            The notification element
427  * @returns The last update time of the notification
428  */
429 function getNotificationLastUpdatedTime(notificationElement) {
430         return $(notificationElement).prop("lastUpdatedTime");
431 }
432
433 function likePost(postId) {
434         ajaxGet("like.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data) {
435                 if ((data == null) || !data.success) {
436                         return;
437                 }
438                 sone.find(".post#post-" + postId + " > .inner-part > .status-line .like").addClass("hidden");
439                 sone.find(".post#post-" + postId + " > .inner-part > .status-line .unlike").removeClass("hidden");
440                 updatePostLikes(postId);
441         }, function() {
442                 /* ignore error. */
443         });
444 }
445
446 function unlikePost(postId) {
447         ajaxGet("unlike.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data) {
448                 if ((data == null) || !data.success) {
449                         return;
450                 }
451                 sone.find(".post#post-" + postId + " > .inner-part > .status-line .unlike").addClass("hidden");
452                 sone.find(".post#post-" + postId + " > .inner-part > .status-line .like").removeClass("hidden");
453                 updatePostLikes(postId);
454         }, function() {
455                 /* ignore error. */
456         });
457 }
458
459 function updatePostLikes(postId) {
460         ajaxGet("getLikes.ajax", { "type": "post", "post": postId }, function(data) {
461                 if ((data != null) && data.success) {
462                         sone.find(".post#post-" + postId + " > .inner-part > .status-line .likes").toggleClass("hidden", data.likes === 0);
463                         sone.find(".post#post-" + postId + " > .inner-part > .status-line .likes span.like-count").text(data.likes);
464                         sone.find(".post#post-" + postId + " > .inner-part > .status-line .likes > span").prop("title", generateSoneList(data.sones));
465                 }
466         }, function() {
467                 /* ignore error. */
468         });
469 }
470
471 function likeReply(replyId) {
472         ajaxGet("like.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data) {
473                 if ((data == null) || !data.success) {
474                         return;
475                 }
476                 sone.find(".reply#reply-" + replyId + " .status-line .like").addClass("hidden");
477                 sone.find(".reply#reply-" + replyId + " .status-line .unlike").removeClass("hidden");
478                 updateReplyLikes(replyId);
479         }, function() {
480                 /* ignore error. */
481         });
482 }
483
484 function unlikeReply(replyId) {
485         ajaxGet("unlike.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data) {
486                 if ((data == null) || !data.success) {
487                         return;
488                 }
489                 sone.find(".reply#reply-" + replyId + " .status-line .unlike").addClass("hidden");
490                 sone.find(".reply#reply-" + replyId + " .status-line .like").removeClass("hidden");
491                 updateReplyLikes(replyId);
492         }, function() {
493                 /* ignore error. */
494         });
495 }
496
497 /**
498  * Trusts the Sone with the given ID.
499  *
500  * @param soneId
501  *            The ID of the Sone to trust
502  */
503 function trustSone(soneId) {
504         ajaxGet("trustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data) {
505                 if ((data != null) && data.success) {
506                         updateTrustControls(soneId, data.trustValue);
507                 }
508         });
509 }
510
511 /**
512  * Distrusts the Sone with the given ID, i.e. assigns a negative trust value.
513  *
514  * @param soneId
515  *            The ID of the Sone to distrust
516  */
517 function distrustSone(soneId) {
518         ajaxGet("distrustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data) {
519                 if ((data != null) && data.success) {
520                         updateTrustControls(soneId, data.trustValue);
521                 }
522         });
523 }
524
525 /**
526  * Untrusts the Sone with the given ID, i.e. removes any trust assignment.
527  *
528  * @param soneId
529  *            The ID of the Sone to untrust
530  */
531 function untrustSone(soneId) {
532         ajaxGet("untrustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data) {
533                 if ((data != null) && data.success) {
534                         updateTrustControls(soneId, data.trustValue);
535                 }
536         });
537 }
538
539 /**
540  * Updates the trust controls for all posts and replies of the given Sone,
541  * according to the given trust value.
542  *
543  * @param soneId
544  *            The ID of the Sone to update all trust controls for
545  * @param trustValue
546  *            The trust value for the Sone
547  */
548 function updateTrustControls(soneId, trustValue) {
549         sone.find(".post").each(function() {
550                 if (getPostAuthor(this) === soneId) {
551                         getPostElement(this).find(".post-trust").toggleClass("hidden", trustValue != null);
552                         getPostElement(this).find(".post-distrust").toggleClass("hidden", trustValue != null);
553                         getPostElement(this).find(".post-untrust").toggleClass("hidden", trustValue == null);
554                 }
555         });
556         sone.find(".reply").each(function() {
557                 if (getReplyAuthor(this) === soneId) {
558                         getReplyElement(this).find(".reply-trust").toggleClass("hidden", trustValue != null);
559                         getReplyElement(this).find(".reply-distrust").toggleClass("hidden", trustValue != null);
560                         getReplyElement(this).find(".reply-untrust").toggleClass("hidden", trustValue == null);
561                 }
562         });
563 }
564
565 /**
566  * Bookmarks the post with the given ID.
567  *
568  * @param postId
569  *            The ID of the post to bookmark
570  */
571 function bookmarkPost(postId) {
572         (function(postId) {
573                 ajaxGet("bookmark.ajax", {"formPassword": getFormPassword(), "type": "post", "post": postId}, function(data) {
574                         if ((data != null) && data.success) {
575                                 getPost(postId).find(".bookmark").toggleClass("hidden", true);
576                                 getPost(postId).find(".unbookmark").toggleClass("hidden", false);
577                         }
578                 });
579         })(postId);
580 }
581
582 /**
583  * Unbookmarks the post with the given ID.
584  *
585  * @param postId
586  *            The ID of the post to unbookmark
587  */
588 function unbookmarkPost(postId) {
589         ajaxGet("unbookmark.ajax", {"formPassword": getFormPassword(), "type": "post", "post": postId}, function(data) {
590                 if ((data != null) && data.success) {
591                         getPost(postId).find(".bookmark").toggleClass("hidden", false);
592                         getPost(postId).find(".unbookmark").toggleClass("hidden", true);
593                 }
594         });
595 }
596
597 function updateReplyLikes(replyId) {
598         ajaxGet("getLikes.ajax", { "type": "reply", "reply": replyId }, function(data) {
599                 if ((data != null) && data.success) {
600                         sone.find(".reply#reply-" + replyId + " .status-line .likes").toggleClass("hidden", data.likes === 0);
601                         sone.find(".reply#reply-" + replyId + " .status-line .likes span.like-count").text(data.likes);
602                         sone.find(".reply#reply-" + replyId + " .status-line .likes > span").prop("title", generateSoneList(data.sones));
603                 }
604         }, function() {
605                 /* ignore error. */
606         });
607 }
608
609 /**
610  * Posts a reply and calls the given callback when the request finishes.
611  *
612  * @param sender
613  *            The ID of the sender
614  * @param postId
615  *            The ID of the post the reply refers to
616  * @param text
617  *            The text to post
618  * @param callbackFunction
619  *            The callback function to call when the request finishes (takes 3
620  *            parameters: success, error, replyId)
621  */
622 function postReply(sender, postId, text, callbackFunction) {
623         ajaxGet("createReply.ajax", { "formPassword" : getFormPassword(), "sender": sender, "post" : postId, "text": text }, function(data) {
624                 if (data == null) {
625                         /* TODO - show error */
626                         return;
627                 }
628                 if (data.success) {
629                         callbackFunction(true, null, data.reply, data.sone);
630                 } else {
631                         callbackFunction(false, data.error);
632                 }
633         }, function() {
634                 /* ignore error. */
635         });
636 }
637
638 /**
639  * Ajaxifies the given Sone by enhancing all eligible elements with AJAX.
640  *
641  * @param soneElement
642  *            The Sone to ajaxify
643  */
644 function ajaxifySone(soneElement) {
645         /*
646          * convert all â€śfollow”, â€śunfollow”, â€ślock”, and â€śunlock” links to something
647          * nicer.
648          */
649         $(".follow", soneElement).submit(function() {
650                 const followElement = this;
651                 ajaxGet("followSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
652                         $(followElement).addClass("hidden");
653                         $(followElement).parent().find(".unfollow").removeClass("hidden");
654                 });
655                 return false;
656         });
657         $(".unfollow", soneElement).submit(function() {
658                 const unfollowElement = this;
659                 ajaxGet("unfollowSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
660                         $(unfollowElement).addClass("hidden");
661                         $(unfollowElement).parent().find(".follow").removeClass("hidden");
662                 });
663                 return false;
664         });
665         $(".lock", soneElement).submit(function() {
666                 const lockElement = this;
667                 ajaxGet("lockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
668                         $(lockElement).addClass("hidden");
669                         $(lockElement).parent().find(".unlock").removeClass("hidden");
670                 });
671                 return false;
672         });
673         $(".unlock", soneElement).submit(function() {
674                 const unlockElement = this;
675                 ajaxGet("unlockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
676                         $(unlockElement).addClass("hidden");
677                         $(unlockElement).parent().find(".lock").removeClass("hidden");
678                 });
679                 return false;
680         });
681
682         /* mark Sone as known when clicking it. */
683         $(soneElement).click(function() {
684                 markSoneAsKnown(this);
685         });
686 }
687
688 const followSone = function(soneId) {
689         const followElement = this;
690         ajaxGet("followSone.ajax", { "sone": soneId, "formPassword": getFormPassword() }, function() {
691                 $(followElement).addClass("hidden");
692                 $(followElement).parent().find(".unfollow").removeClass("hidden");
693                 sone.find(".sone-menu").each(function() {
694                         if (getMenuSone(this) === soneId) {
695                                 $(".follow", this).toggleClass("hidden", true);
696                                 $(".unfollow", this).toggleClass("hidden", false);
697                         }
698                 });
699         });
700         return false;
701 };
702
703 const unfollowSone = function (soneId) {
704         const unfollowElement = this;
705         ajaxGet("unfollowSone.ajax", {"sone": soneId, "formPassword": getFormPassword()}, function () {
706                 $(unfollowElement).addClass("hidden");
707                 $(unfollowElement).parent().find(".follow").removeClass("hidden");
708                 sone.find(".sone-menu").each(function () {
709                         if (getMenuSone(this) === soneId) {
710                                 $(".follow", this).toggleClass("hidden", false);
711                                 $(".unfollow", this).toggleClass("hidden", true);
712                         }
713                 });
714         });
715         return false;
716 };
717
718 /**
719  * Ajaxifies the given post by enhancing all eligible elements with AJAX.
720  *
721  * @param postElement
722  *            The post element to ajaxify
723  */
724 function ajaxifyPost(postElement) {
725         $(postElement).find("form").submit(function() {
726                 return false;
727         });
728         $(postElement).find(".create-reply button:submit").click(function() {
729                 const button = $(this);
730                 button.prop("disabled", "disabled");
731                 const sender = $(this.form).find(":input[name=sender]").val();
732                 const inputField = $(this.form).find(":input[name=text]:enabled").get(0);
733                 const postId = getPostId(this);
734                 const text = $(inputField).val();
735                 (function(sender, postId, text, inputField) {
736                         postReply(sender, postId, text, function(success, error, replyId, soneId) {
737                                 if (success) {
738                                         $(inputField).val("");
739                                         loadNewReply(replyId, soneId, postId);
740                                         sone.find(".post#post-" + postId + " .create-reply").addClass("hidden");
741                                         sone.find(".post#post-" + postId + " .create-reply .sender").hide();
742                                         sone.find(".post#post-" + postId + " .create-reply .select-sender").show();
743                                         sone.find(".post#post-" + postId + " .create-reply :input[name=sender]").val(getCurrentSoneId());
744                                         updateReplyTimes(replyId);
745                                 } else {
746                                         alert(error);
747                                 }
748                                 button.removeAttr("disabled");
749                         });
750                 })(sender, postId, text, inputField);
751                 return false;
752         });
753
754         /* replace all â€śdelete” buttons with javascript. */
755         (function(postElement) {
756                 getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
757                         const postId = getPostId(postElement);
758                         enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
759                 });
760         })(postElement);
761
762         /* convert all â€ślike” buttons to javascript functions. */
763         $(postElement).find(".like-post").submit(function() {
764                 likePost(getPostId(this));
765                 return false;
766         });
767         $(postElement).find(".unlike-post").submit(function() {
768                 unlikePost(getPostId(this));
769                 return false;
770         });
771
772         /* convert trust control buttons to javascript functions. */
773         $(postElement).find(".post-trust").submit(function() {
774                 trustSone(getPostAuthor(this));
775                 return false;
776         });
777         $(postElement).find(".post-distrust").submit(function() {
778                 distrustSone(getPostAuthor(this));
779                 return false;
780         });
781         $(postElement).find(".post-untrust").submit(function() {
782                 untrustSone(getPostAuthor(this));
783                 return false;
784         });
785
786         /* convert bookmark/unbookmark buttons to javascript functions. */
787         $(postElement).find(".bookmark").submit(function() {
788                 bookmarkPost(getPostId(this));
789                 return false;
790         });
791         $(postElement).find(".unbookmark").submit(function() {
792                 unbookmarkPost(getPostId(this));
793                 return false;
794         });
795
796         /* convert â€śshow source” link into javascript function. */
797         $(postElement).find(".show-source").each(function() {
798                 $("a", this).click(function() {
799                         const post = getPostElement(this);
800                         const rawPostText = $(".post-text.raw-text", post);
801                         rawPostText.toggleClass("hidden");
802                         if (rawPostText.hasClass("hidden")) {
803                                 $(".post-text.short-text", post).removeClass("hidden");
804                                 $(".post-text.text", post).addClass("hidden");
805                                 $(".expand-post-text", post).removeClass("hidden");
806                                 $(".shrink-post-text", post).addClass("hidden");
807                         } else {
808                                 $(".post-text.short-text", post).addClass("hidden");
809                                 $(".post-text.text", post).addClass("hidden");
810                                 $(".expand-post-text", post).addClass("hidden");
811                                 $(".shrink-post-text", post).addClass("hidden");
812                         }
813                         return false;
814                 });
815         });
816
817         /* convert â€śshow more” link into javascript function. */
818         const toggleShowMore = function() {
819                 $(this).click(function() {
820                         $(".post-text.text", getPostElement(this)).toggleClass("hidden");
821                         $(".post-text.short-text", getPostElement(this)).toggleClass("hidden");
822                         $(".expand-post-text", getPostElement(this)).toggleClass("hidden");
823                         $(".shrink-post-text", getPostElement(this)).toggleClass("hidden");
824                         return false;
825                 });
826         };
827         $(postElement).find(".expand-post-text").each(toggleShowMore);
828         $(postElement).find(".shrink-post-text").each(toggleShowMore);
829
830         /* ajaxify author/post links */
831         $(".post-status-line .permalink a", postElement).click(function() {
832                 if (!$(".create-reply", postElement).hasClass("hidden")) {
833                         const textArea = $(":input.reply-input", postElement).focus().data("textarea");
834                         $(textArea).replaceSelection($(this).prop("href"));
835                 }
836                 return false;
837         });
838
839         /* add â€ścomment” link. */
840         addCommentLink(getPostId(postElement), getPostAuthor(postElement), postElement, $(postElement).find(".post-status-line .permalink-author"));
841
842         /* process all replies. */
843         const replyIds = [];
844         $(postElement).find(".reply").each(function() {
845                 replyIds.push(getReplyId(this));
846                 ajaxifyReply(this);
847         });
848         updateReplyTimes(replyIds.join(","));
849
850         /* process reply input fields. */
851         getTranslation("WebInterface.DefaultText.Reply", function(text) {
852                 $(postElement).find(":input.reply-input").each(function() {
853                         registerInputTextareaSwap(this, text, "text", false, false);
854                 });
855         });
856
857         /* process sender selection. */
858         $(".select-sender", postElement).css("display", "inline");
859         $(".sender", postElement).hide();
860         $(".select-sender button", postElement).click(function() {
861                 $(".sender", postElement).show();
862                 $(".select-sender", postElement).hide();
863                 return false;
864         });
865
866         /* mark everything as known on click. */
867         (function(postElement) {
868                 $(postElement).click(function(event) {
869                         if ($(event.target).hasClass("click-to-show")) {
870                                 return false;
871                         }
872                         markPostAsKnown(postElement, false);
873                 });
874         })(postElement);
875
876         /* hide reply input field. */
877         $(postElement).find(".create-reply").addClass("hidden");
878
879         /* show Sone menu when hovering over the avatar. */
880         $(postElement).find(".post-avatar").mouseover(function() {
881                 if (typeof currentSoneMenuTimeoutHandler !== undefined) {
882                         clearTimeout(currentSoneMenuTimeoutHandler);
883                 }
884                 currentSoneMenuId = getPostId(this);
885                 currentSoneMenuTimeoutHandler = setTimeout(function() {
886                         $(".sone-menu:visible").fadeOut();
887                         $(".sone-post-menu", postElement).mouseleave(function() {
888                                 $(this).fadeOut();
889                         }).fadeIn();
890                 }, 1000);
891         }).mouseleave(function() {
892                 if (currentSoneMenuId === getPostId(this)) {
893                         clearTimeout(currentSoneMenuTimeoutHandler);
894                 }
895         });
896         (function(postElement) {
897                 const soneId = $(".sone-menu-id:first", postElement).text();
898                 $(".sone-post-menu .follow", postElement).click(followSone(soneId));
899                 $(".sone-post-menu .unfollow", postElement).click(unfollowSone(soneId));
900         })(postElement);
901 }
902
903 /**
904  * Ajaxifies the given reply element.
905  *
906  * @param replyElement
907  *            The reply element to ajaxify
908  */
909 function ajaxifyReply(replyElement) {
910         $(replyElement).find(".like-reply").submit(function() {
911                 likeReply(getReplyId(this));
912                 return false;
913         });
914         $(replyElement).find(".unlike-reply").submit(function() {
915                 unlikeReply(getReplyId(this));
916                 return false;
917         });
918         (function(replyElement) {
919                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
920                         $(replyElement).find(".delete-reply button").each(function() {
921                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
922                         });
923                 });
924         })(replyElement);
925
926         /* ajaxify author links */
927         $(".reply-status-line .permalink a", replyElement).click(function() {
928                 if (!$(".create-reply", getPostElement(replyElement)).hasClass("hidden")) {
929                         const textArea = $(":input.reply-input", getPostElement(replyElement)).focus().data("textarea");
930                         $(textArea).replaceSelection($(this).prop("href"));
931                 }
932                 return false;
933         });
934
935         addCommentLink(getPostId(replyElement), getReplyAuthor(replyElement), replyElement, $(replyElement).find(".reply-status-line .permalink-author"));
936
937         /* convert â€śshow source” link into javascript function. */
938         $(replyElement).find(".show-reply-source").each(function() {
939                 $("a", this).click(function() {
940                         const reply = getReplyElement(this);
941                         const rawReplyText = $(".reply-text.raw-text", reply);
942                         rawReplyText.toggleClass("hidden");
943                         if (rawReplyText.hasClass("hidden")) {
944                                 $(".reply-text.short-text", reply).removeClass("hidden");
945                                 $(".reply-text.text", reply).addClass("hidden");
946                                 $(".expand-reply-text", reply).removeClass("hidden");
947                                 $(".shrink-reply-text", reply).addClass("hidden");
948                         } else {
949                                 $(".reply-text.short-text", reply).addClass("hidden");
950                                 $(".reply-text.text", reply).addClass("hidden");
951                                 $(".expand-reply-text", reply).addClass("hidden");
952                                 $(".shrink-reply-text", reply).addClass("hidden");
953                         }
954                         return false;
955                 });
956         });
957
958         /* convert â€śshow more” link into javascript function. */
959         const toggleShowMore = function() {
960                 $(this).click(function() {
961                         $(".reply-text.text", getReplyElement(this)).toggleClass("hidden");
962                         $(".reply-text.short-text", getReplyElement(this)).toggleClass("hidden");
963                         $(".expand-reply-text", getReplyElement(this)).toggleClass("hidden");
964                         $(".shrink-reply-text", getReplyElement(this)).toggleClass("hidden");
965                         return false;
966                 });
967         };
968         $(replyElement).find(".expand-reply-text").each(toggleShowMore);
969         $(replyElement).find(".shrink-reply-text").each(toggleShowMore);
970
971         /* convert trust control buttons to javascript functions. */
972         $(replyElement).find(".reply-trust").submit(function() {
973                 trustSone(getReplyAuthor(this));
974                 return false;
975         });
976         $(replyElement).find(".reply-distrust").submit(function() {
977                 distrustSone(getReplyAuthor(this));
978                 return false;
979         });
980         $(replyElement).find(".reply-untrust").submit(function() {
981                 untrustSone(getReplyAuthor(this));
982                 return false;
983         });
984
985         /* show Sone menu when hovering over the avatar. */
986         $(replyElement).find(".reply-avatar").mouseover(function() {
987                 if (typeof currentSoneMenuTimeoutHandler !== undefined) {
988                         clearTimeout(currentSoneMenuTimeoutHandler);
989                 }
990                 currentSoneMenuId = getPostId(this) + "-" + getReplyId(this);
991                 currentSoneMenuTimeoutHandler = setTimeout(function() {
992                         $(".sone-menu:visible").fadeOut();
993                         $(".sone-reply-menu", replyElement).mouseleave(function() {
994                                 $(this).fadeOut();
995                         }).fadeIn();
996                 }, 1000);
997         }).mouseleave(function() {
998                 if (currentSoneMenuId === getPostId(this) + "-" + getReplyId(this)) {
999                         clearTimeout(currentSoneMenuTimeoutHandler);
1000                 }
1001         });
1002         (function(replyElement) {
1003                 const soneId = $(".sone-menu-id", replyElement).text();
1004                 $(".sone-menu .follow", replyElement).click(followSone(soneId));
1005                 $(".sone-menu .unfollow", replyElement).click(unfollowSone(soneId));
1006         })(replyElement);
1007 }
1008
1009 /**
1010  * Ajaxifies the given notification by replacing the form with AJAX.
1011  *
1012  * @param notification
1013  *            jQuery object representing the notification.
1014  */
1015 function ajaxifyNotification(notification) {
1016         notification.find("form").submit(function() {
1017                 return false;
1018         });
1019         notification.find("input[name=returnPage]").val($.url.attr("relative"));
1020         if (notification.find(".short-text").length > 0) {
1021                 notification.find(".short-text").removeClass("hidden");
1022                 notification.find(".text").addClass("hidden");
1023         }
1024         notification.find("form.mark-as-read button").click(function() {
1025                 const allIds = $(":input[name=id]", this.form).val().split(" ");
1026                 for (let index = 0; index < allIds.length; index += 16) {
1027                         const ids = allIds.slice(index, index + 16).join(" ");
1028                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": $(":input[name=type]", this.form).val(), "id": ids});
1029                 }
1030         });
1031         notification.find("a[class^='link-']").each(function() {
1032                 const linkElement = $(this);
1033                 if (linkElement.is("[href^='viewPost']")) {
1034                         const id = linkElement.prop("class").substr(5);
1035                         if (hasPost(id)) {
1036                                 linkElement.prop("href", "#post-" + id).addClass("in-page-link");
1037                         }
1038                 }
1039         });
1040         notification.find("form.dismiss button").click(function() {
1041                 ajaxGet("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.prop("id") }, function() {
1042                         /* dismiss in case of error, too. */
1043                         notification.slideUp();
1044                 }, function() {
1045                         /* ignore error. */
1046                 });
1047         });
1048         return notification;
1049 }
1050
1051 /**
1052  * Returns the notification hash. This hash is used in {@link #getStatus()} to
1053  * determine whether the notifications changed and need to be reloaded.
1054  */
1055 function getNotificationHash() {
1056         return sone.find("#notification-area #notification-hash").text();
1057 }
1058
1059 /**
1060  * Sets the notification hash.
1061  *
1062  * @param notificationHash
1063  *            The new notification hash
1064  */
1065 function setNotificationHash(notificationHash) {
1066         sone.find("#notification-area #notification-hash").text(notificationHash);
1067 }
1068
1069 /**
1070  * Retrieves element IDs from notification elements.
1071  *
1072  * @param notification
1073  *            The notification element
1074  * @param selector
1075  *            The selector of the element containing the ID as text
1076  * @returns All extracted IDs
1077  */
1078 function getElementIds(notification, selector) {
1079         const elementIds = [];
1080         $(selector, notification).each(function() {
1081                 elementIds.push($(this).text());
1082         });
1083         return elementIds;
1084 }
1085
1086 /**
1087  * Compares the given notification elements and calls {@link #markSoneAsKnown()}
1088  * for every ID that is contained in the old notification but not in the new.
1089  *
1090  * @param oldNotification
1091  *            The old notification element
1092  * @param newNotification
1093  *            The new notification element
1094  */
1095 function checkForRemovedSones(oldNotification, newNotification) {
1096         if (getNotificationId(oldNotification) !== "new-sone-notification") {
1097                 return;
1098         }
1099         const oldIds = getElementIds(oldNotification, ".new-sone-id");
1100         const newIds = getElementIds(newNotification, ".new-sone-id");
1101         $.each(oldIds, function(index, value) {
1102                 if ($.inArray(value, newIds) === -1) {
1103                         markSoneAsKnown(getSone(value), true);
1104                 }
1105         });
1106 }
1107
1108 /**
1109  * Compares the given notification elements and calls {@link #markPostAsKnown()}
1110  * for every ID that is contained in the old notification but not in the new.
1111  *
1112  * @param oldNotification
1113  *            The old notification element
1114  * @param newNotification
1115  *            The new notification element
1116  */
1117 function checkForRemovedPosts(oldNotification, newNotification) {
1118         if (getNotificationId(oldNotification) !== "new-post-notification") {
1119                 return;
1120         }
1121         const oldIds = getElementIds(oldNotification, ".post-id");
1122         const newIds = getElementIds(newNotification, ".post-id");
1123         $.each(oldIds, function(index, value) {
1124                 if ($.inArray(value, newIds) === -1) {
1125                         markPostAsKnown(getPost(value), true);
1126                 }
1127         });
1128 }
1129
1130 /**
1131  * Compares the given notification elements and calls
1132  * {@link #markReplyAsKnown()} for every ID that is contained in the old
1133  * notification but not in the new.
1134  *
1135  * @param oldNotification
1136  *            The old notification element
1137  * @param newNotification
1138  *            The new notification element
1139  */
1140 function checkForRemovedReplies(oldNotification, newNotification) {
1141         if (getNotificationId(oldNotification) !== "new-reply-notification") {
1142                 return;
1143         }
1144         const oldIds = getElementIds(oldNotification, ".reply-id");
1145         const newIds = getElementIds(newNotification, ".reply-id");
1146         $.each(oldIds, function(index, value) {
1147                 if ($.inArray(value, newIds) === -1) {
1148                         markReplyAsKnown(getReply(value), true);
1149                 }
1150         });
1151 }
1152
1153 function getStatus() {
1154         const parameters = isViewSonePage() ? {"soneIds": getShownSoneId()} : isKnownSonesPage() ? {"soneIds": getShownSoneIds()} : {};
1155         $.extend(parameters, {
1156                 "elements": JSON.stringify($(".linked-element.not-loaded").map(function () {
1157                         return $(this).prop("title");
1158                 }).toArray())
1159         });
1160         ajaxGet("getStatus.ajax", parameters, function(data) {
1161                 if ((data != null) && data.success) {
1162                         /* process Sone information. */
1163                         $.each(data.sones, function(index, value) {
1164                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdatedUnknown ? null : value.lastUpdated, value.lastUpdatedText);
1165                         });
1166                         notLoggedIn = !data.loggedIn;
1167                         if (!notLoggedIn) {
1168                                 showOfflineMarker(!online);
1169                         }
1170                         if (data.notificationHash !== getNotificationHash()) {
1171                                 console.log("Old hash: ", getNotificationHash(), ", new hash: ", data.notificationHash);
1172                                 requestNotifications();
1173                                 /* process new posts. */
1174                                 $.each(data.newPosts, function(index, value) {
1175                                         loadNewPost(value.id, value.sone, value.recipient, value.time);
1176                                 });
1177                                 /* process new replies. */
1178                                 $.each(data.newReplies, function(index, value) {
1179                                         loadNewReply(value.id, value.sone, value.post);
1180                                 });
1181                         }
1182                         if (data.linkedElements) {
1183                                 loadLinkedElements(data.linkedElements)
1184                         }
1185                         /* do it again in 5 seconds. */
1186                         setTimeout(getStatus, 5000);
1187                 } else {
1188                         /* data.success was false, wait 30 seconds. */
1189                         setTimeout(getStatus, 30000);
1190                 }
1191         }, function() {
1192                 statusRequestQueued = false;
1193                 ajaxError();
1194         });
1195 }
1196
1197 function requestNotifications() {
1198         ajaxGet("getNotifications.ajax", {}, function(data) {
1199                 if (data && data.success) {
1200                         /* search for removed notifications. */
1201                         sone.find("#notification-area .notification").each(function() {
1202                                 const notificationId = $(this).prop("id");
1203                                 let foundNotification = false;
1204                                 $.each(data.notifications, function(index, value) {
1205                                         if (value.id === notificationId) {
1206                                                 foundNotification = true;
1207                                                 return false;
1208                                         }
1209                                 });
1210                                 if (!foundNotification) {
1211                                         if (notificationId === "new-sone-notification" && (data.options["ShowNotification/NewSones"] === true)) {
1212                                                 $(".new-sone-id", this).each(function() {
1213                                                         const soneId = $(this).text();
1214                                                         markSoneAsKnown(getSone(soneId), true);
1215                                                 });
1216                                         } else if (notificationId === "new-post-notification" && (data.options["ShowNotification/NewPosts"] === true)) {
1217                                                 $(".post-id", this).each(function() {
1218                                                         const postId = $(this).text();
1219                                                         markPostAsKnown(getPost(postId), true);
1220                                                 });
1221                                         } else if (notificationId === "new-reply-notification" && (data.options["ShowNotification/NewReplies"] === true)) {
1222                                                 $(".reply-id", this).each(function() {
1223                                                         const replyId = $(this).text();
1224                                                         markReplyAsKnown(getReply(replyId), true);
1225                                                 });
1226                                         }
1227                                         $(this).slideUp("normal", function() {
1228                                                 $(this).remove();
1229                                                 /* remove activity when no notifications are visible. */
1230                                                 if (sone.find("#notification-area .notification").length === 0) {
1231                                                         resetActivity();
1232                                                 }
1233                                         });
1234                                 }
1235                         });
1236                         /* process notifications. */
1237                         $.each(data.notifications, function(index, value) {
1238                                 const oldNotification = getNotification(value.id);
1239                                 const notification = ajaxifyNotification(createNotification(value.id, value.lastUpdatedTime, value.text, value.dismissable)).hide();
1240                                 if (oldNotification.length !== 0) {
1241                                         if ((oldNotification.find(".short-text").length > 0) && (notification.find(".short-text").length > 0)) {
1242                                                 const opened = oldNotification.is(":visible") && oldNotification.find(".short-text").hasClass("hidden");
1243                                                 notification.find(".short-text").toggleClass("hidden", opened);
1244                                                 notification.find(".text").toggleClass("hidden", !opened);
1245                                         }
1246                                         checkForRemovedSones(oldNotification, notification);
1247                                         checkForRemovedPosts(oldNotification, notification);
1248                                         checkForRemovedReplies(oldNotification, notification);
1249                                         oldNotification.replaceWith(notification.show());
1250                                 } else {
1251                                         sone.find("#notification-area").append(notification);
1252                                         if (value.id.substring(0, 5) !== "local") {
1253                                                 notification.slideDown();
1254                                                 setActivity();
1255                                         }
1256                                 }
1257                         });
1258                         setNotificationHash(data.notificationHash);
1259                 }
1260         });
1261 }
1262
1263 /**
1264  * Returns the ID of the currently logged in Sone.
1265  *
1266  * @return The ID of the current Sone, or an empty string if no Sone is logged
1267  *         in
1268  */
1269 function getCurrentSoneId() {
1270         return $("#currentSoneId").text();
1271 }
1272
1273 /**
1274  * Returns the content of the page-id attribute.
1275  *
1276  * @returns The page ID
1277  */
1278 function getPageId() {
1279         return sone.find(".page-id").text();
1280 }
1281
1282 /**
1283  * Returns whether the current page is the index page.
1284  *
1285  * @returns {Boolean} <code>true</code> if the current page is the index page,
1286  *          <code>false</code> otherwise
1287  */
1288 function isIndexPage() {
1289         return getPageId() === "index";
1290 }
1291
1292 /**
1293  * Returns the current page of the selected pagination. If no pagination can be
1294  * found with the given selector, {@code 1} is returned.
1295  *
1296  * @param paginationSelector
1297  *            The pagination selector
1298  * @returns The current page of the pagination
1299  */
1300 function getPage(paginationSelector) {
1301         const pagination = $(paginationSelector);
1302         if (pagination.length > 0) {
1303                 return $(".current-page", paginationSelector).text();
1304         }
1305         return 1;
1306 }
1307
1308 /**
1309  * Returns whether the current page is a â€śview Sone” page.
1310  *
1311  * @returns {Boolean} <code>true</code> if the current page is a â€śview Sone”
1312  *          page, <code>false</code> otherwise
1313  */
1314 function isViewSonePage() {
1315         return getPageId() === "view-sone";
1316 }
1317
1318 /**
1319  * Returns the ID of the currently shown Sone. This will only return a sensible
1320  * value if isViewSonePage() returns <code>true</code>.
1321  *
1322  * @returns The ID of the currently shown Sone
1323  */
1324 function getShownSoneId() {
1325         return sone.find(".sone-id").first().text();
1326 }
1327
1328 /**
1329  * Returns the ID of all currently visible Sones. This is mainly used on the
1330  * â€śKnown Sones” page.
1331  *
1332  * @returns The ID of the currently shown Sones
1333  */
1334 function getShownSoneIds() {
1335         const soneIds = [];
1336         sone.find("#known-sones .sone .id").each(function() {
1337                 soneIds.push($(this).text());
1338         });
1339         return soneIds.join(",");
1340 }
1341
1342 /**
1343  * Returns whether the current page is a â€śview post” page.
1344  *
1345  * @returns {Boolean} <code>true</code> if the current page is a â€śview post”
1346  *          page, <code>false</code> otherwise
1347  */
1348 function isViewPostPage() {
1349         return getPageId() === "view-post";
1350 }
1351
1352 /**
1353  * Returns the ID of the currently shown post. This will only return a sensible
1354  * value if isViewPostPage() returns <code>true</code>.
1355  *
1356  * @returns The ID of the currently shown post
1357  */
1358 function getShownPostId() {
1359         return sone.find(".post-id").text();
1360 }
1361
1362 /**
1363  * Returns whether the current page is the â€śknown Sones” page.
1364  *
1365  * @returns {Boolean} <code>true</code> if the current page is the â€śknown
1366  *          Sones” page, <code>false</code> otherwise
1367  */
1368 function isKnownSonesPage() {
1369         return getPageId() === "known-sones";
1370 }
1371
1372 /**
1373  * Returns whether a post with the given ID exists on the current page.
1374  *
1375  * @param postId
1376  *            The post ID to check for
1377  * @returns {Boolean} <code>true</code> if a post with the given ID already
1378  *          exists on the page, <code>false</code> otherwise
1379  */
1380 function hasPost(postId) {
1381         return $(".post#post-" + postId).length > 0;
1382 }
1383
1384 /**
1385  * Returns whether a reply with the given ID exists on the current page.
1386  *
1387  * @param replyId
1388  *            The reply ID to check for
1389  * @returns {Boolean} <code>true</code> if a reply with the given ID already
1390  *          exists on the page, <code>false</code> otherwise
1391  */
1392 function hasReply(replyId) {
1393         return sone.find(".reply#reply-" + replyId).length > 0;
1394 }
1395
1396 function loadNewPost(postId, soneId, recipientId, time) {
1397         if (hasPost(postId)) {
1398                 return;
1399         }
1400         if (!isIndexPage() || (getPage(".pagination-index") > 1)) {
1401                 if (!isViewPostPage() || (getShownPostId() !== postId)) {
1402                         if (!isViewSonePage() || ((getShownSoneId() !== soneId) && (getShownSoneId() !== recipientId)) || (getPage(".post-navigation") > 1)) {
1403                                 return;
1404                         }
1405                 }
1406         }
1407         if (getPostTime(sone.find(".post").last()) > time) {
1408                 return;
1409         }
1410         ajaxGet("getPost.ajax", { "post" : postId }, function(data) {
1411                 if ((data != null) && data.success) {
1412                         if (hasPost(data.post.id)) {
1413                                 return;
1414                         }
1415                         if ((!isIndexPage() || (getPage(".pagination-index") > 1)) && !(isViewSonePage() && ((getShownSoneId() === data.post.sone) || (getShownSoneId() === data.post.recipient) || (getPage(".post-navigation") > 1)))) {
1416                                 return;
1417                         }
1418                         let firstOlderPost = null;
1419                         sone.find(".post").each(function() {
1420                                 if (getPostTime(this) < data.post.time) {
1421                                         firstOlderPost = $(this);
1422                                         return false;
1423                                 }
1424                         });
1425                         const newPost = $(data.post.html).addClass("hidden");
1426                         if ($(".post-author-local", newPost).text() === "true") {
1427                                 newPost.removeClass("new");
1428                         }
1429                         if (firstOlderPost != null) {
1430                                 newPost.insertBefore(firstOlderPost);
1431                         }
1432                         ajaxifyPost(newPost);
1433                         updatePostTimes(data.post.id);
1434                         newPost.slideDown();
1435                         setActivity();
1436                 }
1437         });
1438 }
1439
1440 function loadNewReply(replyId, soneId, postId) {
1441         if (hasReply(replyId)) {
1442                 return;
1443         }
1444         if (!hasPost(postId)) {
1445                 return;
1446         }
1447         ajaxGet("getReply.ajax", { "reply": replyId }, function(data) {
1448                 /* find post. */
1449                 if ((data != null) && data.success) {
1450                         if (hasReply(data.reply.id)) {
1451                                 return;
1452                         }
1453                         sone.find(".post#post-" + data.reply.postId).each(function() {
1454                                 let firstNewerReply = null;
1455                                 $(this).find(".replies .reply").each(function() {
1456                                         if (getReplyTime(this) > data.reply.time) {
1457                                                 firstNewerReply = $(this);
1458                                                 return false;
1459                                         }
1460                                 });
1461                                 const newReply = $(data.reply.html).addClass("hidden");
1462                                 if ($(".reply-author-local", newReply).text() === "true") {
1463                                         newReply.removeClass("new");
1464                                         (function(newReply) {
1465                                                 setTimeout(function() {
1466                                                         markReplyAsKnown(newReply, false);
1467                                                 }, 5000);
1468                                         })(newReply);
1469                                 }
1470                                 if (firstNewerReply != null) {
1471                                         newReply.insertBefore(firstNewerReply);
1472                                 } else {
1473                                         if ($(this).find(".replies .create-reply")) {
1474                                                 $(this).find(".replies .create-reply").before(newReply);
1475                                         } else {
1476                                                 $(this).find(".replies").append(newReply);
1477                                         }
1478                                 }
1479                                 ajaxifyReply(newReply);
1480                                 updateReplyTimes(data.reply.id);
1481                                 newReply.slideDown();
1482                                 setActivity();
1483                                 return false;
1484                         });
1485                 }
1486         });
1487 }
1488
1489 function loadLinkedElements(links) {
1490         const failedElements = links.filter(function(element) {
1491                 return element.failed;
1492         });
1493         if (failedElements.length > 0) {
1494                 failedElements.forEach(function(element) {
1495                         getLinkedElements(element.link).each(function() {
1496                                 $(this).remove()
1497                         });
1498                 });
1499         }
1500         const loadedElements = links.filter(function(element) {
1501                 return !element.loading && !element.failed;
1502         });
1503         if (loadedElements.length > 0) {
1504                 ajaxGet("getLinkedElement.ajax", {
1505                         "elements": JSON.stringify(loadedElements.map(function(element) {
1506                                 return element.link;
1507                         }))
1508                 }, function (data) {
1509                         if ((data != null) && (data.success)) {
1510                                 data.linkedElements.forEach(function (linkedElement) {
1511                                         getLinkedElements(linkedElement.link).each(function() {
1512                                                 $(this).replaceWith(linkedElement.html);
1513                                         });
1514                                 });
1515                         }
1516                 });
1517         }
1518 }
1519
1520 function getLinkedElements(link) {
1521         return $(".linked-element[title='" + link + "']")
1522 }
1523
1524 /**
1525  * Marks the given Sone as known if it is still new.
1526  *
1527  * @param soneElement
1528  *            The Sone to mark as known
1529  * @param skipRequest
1530  *            true to skip the JSON request, false or omit to perform the JSON
1531  *            request
1532  */
1533 function markSoneAsKnown(soneElement, skipRequest) {
1534         if ($(soneElement).hasClass("new")) {
1535                 $(soneElement).removeClass("new");
1536                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1537                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "sone", "id": getSoneId(soneElement)});
1538                         requestNotifications();
1539                 }
1540         }
1541 }
1542
1543 function markPostAsKnown(postElements, skipRequest) {
1544         $(postElements).each(function() {
1545                 const postElement = this;
1546                 if ($(postElement).hasClass("new") || ((typeof skipRequest != "undefined"))) {
1547                         (function(postElement) {
1548                                 $(postElement).removeClass("new");
1549                                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1550                                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "post", "id": getPostId(postElement)});
1551                                         requestNotifications();
1552                                 }
1553                         })(postElement);
1554                 }
1555                 $(".click-to-show", postElement).removeClass("new");
1556         });
1557         markReplyAsKnown($(postElements).find(".reply"), true);
1558 }
1559
1560 function markReplyAsKnown(replyElements, skipRequest) {
1561         $(replyElements).each(function() {
1562                 const replyElement = this;
1563                 if ($(replyElement).hasClass("new") || ((typeof skipRequest != "undefined"))) {
1564                         (function(replyElement) {
1565                                 $(replyElement).removeClass("new");
1566                                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1567                                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "reply", "id": getReplyId(replyElement)});
1568                                         requestNotifications();
1569                                 }
1570                         })(replyElement);
1571                 }
1572         });
1573 }
1574
1575 /**
1576  * Updates the time of the post with the given ID.
1577  *
1578  * @param postId
1579  *            The ID of the post to update
1580  * @param timeText
1581  *            The text of the time to show
1582  * @param refreshTime
1583  *            The refresh time after which to request a new time (in seconds)
1584  * @param tooltip
1585  *            The tooltip to show
1586  */
1587 function updatePostTime(postId, timeText, refreshTime, tooltip) {
1588         if (!getPost(postId).is(":visible")) {
1589                 return;
1590         }
1591         getPost(postId).find(".post-status-line > .time a").html(timeText).prop("title", tooltip);
1592         (function(postId, refreshTime) {
1593                 setTimeout(function() {
1594                         updatePostTimes(postId);
1595                 }, refreshTime * 1000);
1596         })(postId, refreshTime);
1597 }
1598
1599 /**
1600  * Requests new rendered times for the posts with the given IDs.
1601  *
1602  * @param postIds
1603  *            Comma-separated post IDs
1604  */
1605 function updatePostTimes(postIds) {
1606         if (postIds !== "") {
1607         ajaxGet("getTimes.ajax", {"posts": postIds}, function (data) {
1608             if ((data != null) && data.success) {
1609                 $.each(data.postTimes, function (index, value) {
1610                     updatePostTime(index, value.timeText, value.refreshTime, value.tooltip);
1611                 });
1612             }
1613         });
1614     }
1615 }
1616
1617 /**
1618  * Updates the time of the reply with the given ID.
1619  *
1620  * @param postId
1621  *            The ID of the reply to update
1622  * @param timeText
1623  *            The text of the time to show
1624  * @param refreshTime
1625  *            The refresh time after which to request a new time (in seconds)
1626  * @param tooltip
1627  *            The tooltip to show
1628  */
1629 function updateReplyTime(replyId, timeText, refreshTime, tooltip) {
1630         getReply(replyId).find(".reply-status-line > .time").html(timeText).prop("title", tooltip);
1631         (function(replyId, refreshTime) {
1632                 setTimeout(function() {
1633                         updateReplyTimes(replyId);
1634                 }, refreshTime * 1000);
1635         })(replyId, refreshTime);
1636 }
1637
1638 /**
1639  * Requests new rendered times for the posts with the given IDs.
1640  *
1641  * @param postIds
1642  *            Comma-separated post IDs
1643  */
1644 function updateReplyTimes(replyIds) {
1645         if (replyIds !== "") {
1646         ajaxGet("getTimes.ajax", {"replies": replyIds}, function (data) {
1647             if ((data != null) && data.success) {
1648                 $.each(data.replyTimes, function (index, value) {
1649                     updateReplyTime(index, value.timeText, value.refreshTime, value.tooltip);
1650                 });
1651             }
1652         });
1653     }
1654 }
1655
1656 function resetActivity() {
1657         const title = document.title;
1658         if (title.indexOf('(') === 0) {
1659                 setTitle(title.substr(title.indexOf(' ') + 1));
1660         }
1661         iconBlinking = false;
1662 }
1663
1664 function setActivity() {
1665         if (!focus) {
1666                 const title = document.title;
1667                 if (title.indexOf('(') !== 0) {
1668                         setTitle("(!) " + title);
1669                 }
1670                 if (!iconBlinking) {
1671                         setTimeout(toggleIcon, 1500);
1672                         iconBlinking = true;
1673                 }
1674         }
1675 }
1676
1677 /**
1678  * Sets the window title after a small delay to prevent race-condition issues.
1679  *
1680  * @param title
1681  *            The title to set
1682  */
1683 function setTitle(title) {
1684         setTimeout(function() {
1685                 document.title = title;
1686         }, 50);
1687 }
1688
1689 /** Whether the icon is currently showing activity. */
1690 let iconActive = false;
1691
1692 /** Whether the icon is currently supposed to blink. */
1693 let iconBlinking = false;
1694
1695 /**
1696  * Toggles the icon. If the window has gained focus and the icon is still
1697  * showing the activity state, it is returned to normal.
1698  */
1699 function toggleIcon() {
1700         if (focus || !iconBlinking) {
1701                 if (iconActive) {
1702                         changeIcon("images/icon.png");
1703                         iconActive = false;
1704                 }
1705                 iconBlinking = false;
1706         } else {
1707                 iconActive = !iconActive;
1708                 changeIcon(iconActive ? "images/icon-activity.png" : "images/icon.png");
1709                 setTimeout(toggleIcon, 1500);
1710         }
1711 }
1712
1713 /**
1714  * Changes the icon of the page.
1715  *
1716  * @param iconUrl
1717  *            The new URL of the icon
1718  */
1719 function changeIcon(iconUrl) {
1720         $("link[rel=icon]").remove();
1721         $("head").append($("<link>").prop("rel", "icon").prop("type", "image/png").prop("href", iconUrl));
1722         $("iframe[id=icon-update]")[0].src += "";
1723 }
1724
1725 /**
1726  * Creates a new notification.
1727  *
1728  * @param id
1729  *            The ID of the notificaiton
1730  * @param text
1731  *            The text of the notification
1732  * @param dismissable
1733  *            <code>true</code> if the notification can be dismissed by the
1734  *            user
1735  */
1736 function createNotification(id, lastUpdatedTime, text, dismissable) {
1737         const notification = $("<div></div>").addClass("notification").prop("id", id).prop("lastUpdatedTime", lastUpdatedTime);
1738         if (dismissable) {
1739                 const dismissForm = sone.find("#notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id");
1740                 dismissForm.find("input[name=notification]").val(id);
1741                 notification.append(dismissForm);
1742         }
1743         notification.append(text);
1744         return notification;
1745 }
1746
1747 /**
1748  * Shows the details of the notification with the given ID.
1749  *
1750  * @param notificationId
1751  *            The ID of the notification
1752  */
1753 function showNotificationDetails(notificationId) {
1754         sone.find(".notification#" + notificationId + " .text").removeClass("hidden");
1755         sone.find(".notification#" + notificationId + " .short-text").addClass("hidden");
1756 }
1757
1758 /**
1759  * Deletes the field with the given ID from the profile.
1760  *
1761  * @param fieldId
1762  *            The ID of the field to delete
1763  */
1764 function deleteProfileField(fieldId) {
1765         ajaxGet("deleteProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId}, function(data) {
1766                 if (data && data.success) {
1767                         sone.find(".profile-field#" + data.field.id).slideUp();
1768                 }
1769         });
1770 }
1771
1772 /**
1773  * Renames a profile field.
1774  *
1775  * @param fieldId
1776  *            The ID of the field to rename
1777  * @param newName
1778  *            The new name of the field
1779  * @param successFunction
1780  *            Called when the renaming was successful
1781  */
1782 function editProfileField(fieldId, newName, successFunction) {
1783         ajaxGet("editProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "name": newName}, function(data) {
1784                 if (data && data.success) {
1785                         successFunction();
1786                 }
1787         });
1788 }
1789
1790 /**
1791  * Moves the profile field with the given ID one slot in the given direction.
1792  *
1793  * @param fieldId
1794  *            The ID of the field to move
1795  * @param direction
1796  *            The direction to move in (“up” or â€śdown”)
1797  * @param successFunction
1798  *            Function to call on success
1799  */
1800 function moveProfileField(fieldId, direction, successFunction) {
1801         ajaxGet("moveProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "direction": direction}, function(data) {
1802                 if (data && data.success) {
1803                         successFunction();
1804                 }
1805         });
1806 }
1807
1808 /**
1809  * Moves the profile field with the given ID up one slot.
1810  *
1811  * @param fieldId
1812  *            The ID of the field to move
1813  * @param successFunction
1814  *            Function to call on success
1815  */
1816 function moveProfileFieldUp(fieldId, successFunction) {
1817         moveProfileField(fieldId, "up", successFunction);
1818 }
1819
1820 /**
1821  * Moves the profile field with the given ID down one slot.
1822  *
1823  * @param fieldId
1824  *            The ID of the field to move
1825  * @param successFunction
1826  *            Function to call on success
1827  */
1828 function moveProfileFieldDown(fieldId, successFunction) {
1829         moveProfileField(fieldId, "down", successFunction);
1830 }
1831
1832 let statusRequestQueued = true;
1833
1834 /**
1835  * Sets the status of the web interface as offline.
1836  */
1837 function ajaxError() {
1838         online = false;
1839         showOfflineMarker(true);
1840         if (!statusRequestQueued) {
1841                 setTimeout(getStatus, 5000);
1842                 statusRequestQueued = true;
1843         }
1844 }
1845
1846 /**
1847  * Sets the status of the web interface as online.
1848  */
1849 function ajaxSuccess() {
1850         online = true;
1851         showOfflineMarker(!online || (initiallyLoggedIn && notLoggedIn));
1852 }
1853
1854 /**
1855  * Shows or hides the offline marker.
1856  *
1857  * @param visible
1858  *            {@code true} to display the offline marker, {@code false} to hide
1859  *            it
1860  */
1861 function showOfflineMarker(visible) {
1862         /* jQuery documentation says toggle() works the other way around?! */
1863         sone.find("#offline-marker").toggle(visible);
1864         if (visible) {
1865                 sone.find("#main").addClass("offline");
1866         } else {
1867                 sone.find("#main").removeClass("offline");
1868         }
1869 }
1870
1871 //
1872 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
1873 //
1874
1875 const sone = $("#sone");
1876 let focus = true;
1877 let online = true;
1878 const initiallyLoggedIn = sone.find("#loggedIn").text() === "true";
1879 let notLoggedIn = !initiallyLoggedIn;
1880
1881 /** ID of the next-to-show Sone context menu. */
1882 let currentSoneMenuId;
1883
1884 /** Timeout handler for the next-to-show Sone context menu. */
1885 let currentSoneMenuTimeoutHandler;
1886
1887 $(document).ready(function() {
1888
1889         /* rip out the status update textarea. */
1890         sone.find(".rip-out").each(function() {
1891                 const oldElement = $(this);
1892                 const newElement = $("<input type='text'/>");
1893                 newElement.prop("class", oldElement.prop("class")).prop("name", oldElement.prop("name"));
1894                 oldElement.before(newElement).remove();
1895         });
1896
1897         /* this initializes the status update input field. */
1898         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
1899                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
1900                 sone.find("#update-status .select-sender").css("display", "inline");
1901                 sone.find("#update-status .sender").hide();
1902                 sone.find("#update-status .select-sender button").click(function() {
1903                         sone.find("#update-status .sender").show();
1904                         sone.find("#update-status .select-sender").hide();
1905                         return false;
1906                 });
1907                 sone.find("#update-status").submit(function() {
1908                         const button = $("button:submit", this);
1909                         button.prop("disabled", "disabled");
1910                         if ($(this).find(":input.default:enabled").length > 0) {
1911                                 return false;
1912                         }
1913                         const sender = $(this).find(":input[name=sender]").val();
1914                         const text = $(this).find(":input[name=text]:enabled").val();
1915                         ajaxGet("createPost.ajax", { "formPassword": getFormPassword(), "sender": sender, "text": text }, function() {
1916                                 button.removeAttr("disabled");
1917                         });
1918                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1919                         $(this).find(":input[name=text]:enabled").val("").blur();
1920                         $(this).find(".sender").hide();
1921                         $(this).find(".select-sender").show();
1922                         return false;
1923                 });
1924         });
1925
1926         /* ajaxify the search input field. */
1927         getTranslation("WebInterface.DefaultText.Search", function(defaultText) {
1928                 registerInputTextareaSwap("#sone #search input[name=query]", defaultText, "query", false, true);
1929         });
1930
1931         /* ajaxify input field on â€śview Sone” page. */
1932         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
1933                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
1934                 sone.find("#post-message .select-sender").css("display", "inline");
1935                 sone.find("#post-message .sender").hide();
1936                 sone.find("#post-message .select-sender button").click(function() {
1937                         sone.find("#post-message .sender").show();
1938                         sone.find("#post-message .select-sender").hide();
1939                         return false;
1940                 });
1941                 sone.find("#post-message").submit(function() {
1942                         const sender = $(this).find(":input[name=sender]").val();
1943                         const text = $(this).find(":input[name=text]:enabled").val();
1944                         ajaxGet("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "sender": sender, "text": text });
1945                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1946                         $(this).find(":input[name=text]:enabled").val("").blur();
1947                         $(this).find(".sender").hide();
1948                         $(this).find(".select-sender").show();
1949                         return false;
1950                 });
1951         });
1952
1953         /* Ajaxifies all posts. */
1954         /* calling getTranslation here will cache the necessary values. */
1955         getTranslation("WebInterface.Confirmation.DeletePostButton", function() {
1956                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function() {
1957                         getTranslation("WebInterface.DefaultText.Reply", function() {
1958                 getTranslation("WebInterface.Button.Comment", function () {
1959                     sone.find(".post").each(function() {
1960                                                 ajaxifyPost(this);
1961                                         });
1962                                 });
1963                         });
1964                 });
1965         });
1966
1967         /* update post times. */
1968         const postIds = [];
1969         sone.find(".post").each(function() {
1970                 postIds.push(getPostId(this));
1971         });
1972         updatePostTimes(postIds.join(","));
1973
1974         /* hides all replies but the latest two. */
1975         if (!isViewPostPage()) {
1976                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
1977                         sone.find(".post .replies").each(function() {
1978                                 const allReplies = $(this).find(".reply");
1979                                 if (allReplies.length > 2) {
1980                                         let newHidden = false;
1981                                         for (let replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1982                                                 $(allReplies[replyIndex]).addClass("hidden");
1983                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1984                                         }
1985                                         const clickToShowElement = $("<div></div>").addClass("click-to-show");
1986                                         if (newHidden) {
1987                                                 clickToShowElement.addClass("new");
1988                                         }
1989                                         (function(clickToShowElement, allReplies, text) {
1990                                                 clickToShowElement.text(text);
1991                                                 clickToShowElement.click(function() {
1992                                                         allReplies.removeClass("hidden");
1993                                                         clickToShowElement.addClass("hidden");
1994                                                 });
1995                                         })(clickToShowElement, allReplies, text);
1996                                         $(allReplies[0]).before(clickToShowElement);
1997                                 }
1998                         });
1999                 });
2000         }
2001
2002         sone.find(".sone").each(function() {
2003                 ajaxifySone($(this));
2004         });
2005
2006         /* process all existing notifications, ajaxify dismiss buttons. */
2007         sone.find("#notification-area .notification").each(function() {
2008                 ajaxifyNotification($(this));
2009         });
2010
2011         /* activate status polling. */
2012         setTimeout(getStatus, 5000);
2013
2014         /* reset activity counter when the page has focus. */
2015         $(window).focus(function() {
2016                 focus = true;
2017                 resetActivity();
2018         }).blur(function() {
2019                 focus = false;
2020         });
2021
2022 });