8798aae1c8d1f2d3a2851b8f767dbeb017e2f596
[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 function followSone(soneId) {
689         return function() {
690                 const followElement = this;
691                 ajaxGet("followSone.ajax", {"sone": soneId, "formPassword": getFormPassword()}, function () {
692                         $(followElement).addClass("hidden");
693                         $(followElement).parent().find(".unfollow").removeClass("hidden");
694                         sone.find(".sone-menu").each(function () {
695                                 if (getMenuSone(this) === soneId) {
696                                         $(".follow", this).toggleClass("hidden", true);
697                                         $(".unfollow", this).toggleClass("hidden", false);
698                                 }
699                         });
700                 });
701                 return false;
702         }
703 }
704
705 function unfollowSone(soneId) {
706         return function() {
707                 const unfollowElement = this;
708                 ajaxGet("unfollowSone.ajax", {"sone": soneId, "formPassword": getFormPassword()}, function () {
709                         $(unfollowElement).addClass("hidden");
710                         $(unfollowElement).parent().find(".follow").removeClass("hidden");
711                         sone.find(".sone-menu").each(function () {
712                                 if (getMenuSone(this) === soneId) {
713                                         $(".follow", this).toggleClass("hidden", false);
714                                         $(".unfollow", this).toggleClass("hidden", true);
715                                 }
716                         });
717                 });
718                 return false;
719         }
720 };
721
722 /**
723  * Ajaxifies the given post by enhancing all eligible elements with AJAX.
724  *
725  * @param postElement
726  *            The post element to ajaxify
727  */
728 function ajaxifyPost(postElement) {
729         $(postElement).find("form").submit(function() {
730                 return false;
731         });
732         $(postElement).find(".create-reply button:submit").click(function() {
733                 const button = $(this);
734                 button.prop("disabled", "disabled");
735                 const sender = $(this.form).find(":input[name=sender]").val();
736                 const inputField = $(this.form).find(":input[name=text]:enabled").get(0);
737                 const postId = getPostId(this);
738                 const text = $(inputField).val();
739                 (function(sender, postId, text, inputField) {
740                         postReply(sender, postId, text, function(success, error, replyId, soneId) {
741                                 if (success) {
742                                         $(inputField).val("");
743                                         loadNewReply(replyId, soneId, postId);
744                                         sone.find(".post#post-" + postId + " .create-reply").addClass("hidden");
745                                         sone.find(".post#post-" + postId + " .create-reply .sender").hide();
746                                         sone.find(".post#post-" + postId + " .create-reply .select-sender").show();
747                                         sone.find(".post#post-" + postId + " .create-reply :input[name=sender]").val(getCurrentSoneId());
748                                         updateReplyTimes(replyId);
749                                 } else {
750                                         alert(error);
751                                 }
752                                 button.removeAttr("disabled");
753                         });
754                 })(sender, postId, text, inputField);
755                 return false;
756         });
757
758         /* replace all “delete” buttons with javascript. */
759         (function(postElement) {
760                 getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
761                         const postId = getPostId(postElement);
762                         enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
763                 });
764         })(postElement);
765
766         /* convert all “like” buttons to javascript functions. */
767         $(postElement).find(".like-post").submit(function() {
768                 likePost(getPostId(this));
769                 return false;
770         });
771         $(postElement).find(".unlike-post").submit(function() {
772                 unlikePost(getPostId(this));
773                 return false;
774         });
775
776         /* convert trust control buttons to javascript functions. */
777         $(postElement).find(".post-trust").submit(function() {
778                 trustSone(getPostAuthor(this));
779                 return false;
780         });
781         $(postElement).find(".post-distrust").submit(function() {
782                 distrustSone(getPostAuthor(this));
783                 return false;
784         });
785         $(postElement).find(".post-untrust").submit(function() {
786                 untrustSone(getPostAuthor(this));
787                 return false;
788         });
789
790         /* convert bookmark/unbookmark buttons to javascript functions. */
791         $(postElement).find(".bookmark").submit(function() {
792                 bookmarkPost(getPostId(this));
793                 return false;
794         });
795         $(postElement).find(".unbookmark").submit(function() {
796                 unbookmarkPost(getPostId(this));
797                 return false;
798         });
799
800         /* convert “show source” link into javascript function. */
801         $(postElement).find(".show-source").each(function() {
802                 $("a", this).click(function() {
803                         const post = getPostElement(this);
804                         const rawPostText = $(".post-text.raw-text", post);
805                         rawPostText.toggleClass("hidden");
806                         if (rawPostText.hasClass("hidden")) {
807                                 $(".post-text.short-text", post).removeClass("hidden");
808                                 $(".post-text.text", post).addClass("hidden");
809                                 $(".expand-post-text", post).removeClass("hidden");
810                                 $(".shrink-post-text", post).addClass("hidden");
811                         } else {
812                                 $(".post-text.short-text", post).addClass("hidden");
813                                 $(".post-text.text", post).addClass("hidden");
814                                 $(".expand-post-text", post).addClass("hidden");
815                                 $(".shrink-post-text", post).addClass("hidden");
816                         }
817                         return false;
818                 });
819         });
820
821         /* convert “show more” link into javascript function. */
822         const toggleShowMore = function() {
823                 $(this).click(function() {
824                         $(".post-text.text", getPostElement(this)).toggleClass("hidden");
825                         $(".post-text.short-text", getPostElement(this)).toggleClass("hidden");
826                         $(".expand-post-text", getPostElement(this)).toggleClass("hidden");
827                         $(".shrink-post-text", getPostElement(this)).toggleClass("hidden");
828                         return false;
829                 });
830         };
831         $(postElement).find(".expand-post-text").each(toggleShowMore);
832         $(postElement).find(".shrink-post-text").each(toggleShowMore);
833
834         /* ajaxify author/post links */
835         $(".post-status-line .permalink a", postElement).click(function() {
836                 if (!$(".create-reply", postElement).hasClass("hidden")) {
837                         const textArea = $(":input.reply-input", postElement).focus().data("textarea");
838                         $(textArea).replaceSelection($(this).prop("href"));
839                 }
840                 return false;
841         });
842
843         /* add “comment” link. */
844         addCommentLink(getPostId(postElement), getPostAuthor(postElement), postElement, $(postElement).find(".post-status-line .permalink-author"));
845
846         /* process all replies. */
847         const replyIds = [];
848         $(postElement).find(".reply").each(function() {
849                 replyIds.push(getReplyId(this));
850                 ajaxifyReply(this);
851         });
852         updateReplyTimes(replyIds.join(","));
853
854         /* process reply input fields. */
855         getTranslation("WebInterface.DefaultText.Reply", function(text) {
856                 $(postElement).find(":input.reply-input").each(function() {
857                         registerInputTextareaSwap(this, text, "text", false, false);
858                 });
859         });
860
861         /* process sender selection. */
862         $(".select-sender", postElement).css("display", "inline");
863         $(".sender", postElement).hide();
864         $(".select-sender button", postElement).click(function() {
865                 $(".sender", postElement).show();
866                 $(".select-sender", postElement).hide();
867                 return false;
868         });
869
870         /* mark everything as known on click. */
871         (function(postElement) {
872                 $(postElement).click(function(event) {
873                         if ($(event.target).hasClass("click-to-show")) {
874                                 return false;
875                         }
876                         markPostAsKnown(postElement, false);
877                 });
878         })(postElement);
879
880         /* hide reply input field. */
881         $(postElement).find(".create-reply").addClass("hidden");
882
883         /* show Sone menu when hovering over the avatar. */
884         $(postElement).find(".post-avatar").mouseover(function() {
885                 if (typeof currentSoneMenuTimeoutHandler !== undefined) {
886                         clearTimeout(currentSoneMenuTimeoutHandler);
887                 }
888                 currentSoneMenuId = getPostId(this);
889                 currentSoneMenuTimeoutHandler = setTimeout(function() {
890                         $(".sone-menu:visible").fadeOut();
891                         $(".sone-post-menu", postElement).mouseleave(function() {
892                                 $(this).fadeOut();
893                         }).fadeIn();
894                 }, 1000);
895         }).mouseleave(function() {
896                 if (currentSoneMenuId === getPostId(this)) {
897                         clearTimeout(currentSoneMenuTimeoutHandler);
898                 }
899         });
900         (function(postElement) {
901                 const soneId = $(".sone-menu-id:first", postElement).text();
902                 $(".sone-post-menu .follow", postElement).click(followSone(soneId));
903                 $(".sone-post-menu .unfollow", postElement).click(unfollowSone(soneId));
904         })(postElement);
905 }
906
907 /**
908  * Ajaxifies the given reply element.
909  *
910  * @param replyElement
911  *            The reply element to ajaxify
912  */
913 function ajaxifyReply(replyElement) {
914         $(replyElement).find(".like-reply").submit(function() {
915                 likeReply(getReplyId(this));
916                 return false;
917         });
918         $(replyElement).find(".unlike-reply").submit(function() {
919                 unlikeReply(getReplyId(this));
920                 return false;
921         });
922         (function(replyElement) {
923                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
924                         $(replyElement).find(".delete-reply button").each(function() {
925                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
926                         });
927                 });
928         })(replyElement);
929
930         /* ajaxify author links */
931         $(".reply-status-line .permalink a", replyElement).click(function() {
932                 if (!$(".create-reply", getPostElement(replyElement)).hasClass("hidden")) {
933                         const textArea = $(":input.reply-input", getPostElement(replyElement)).focus().data("textarea");
934                         $(textArea).replaceSelection($(this).prop("href"));
935                 }
936                 return false;
937         });
938
939         addCommentLink(getPostId(replyElement), getReplyAuthor(replyElement), replyElement, $(replyElement).find(".reply-status-line .permalink-author"));
940
941         /* convert “show source” link into javascript function. */
942         $(replyElement).find(".show-reply-source").each(function() {
943                 $("a", this).click(function() {
944                         const reply = getReplyElement(this);
945                         const rawReplyText = $(".reply-text.raw-text", reply);
946                         rawReplyText.toggleClass("hidden");
947                         if (rawReplyText.hasClass("hidden")) {
948                                 $(".reply-text.short-text", reply).removeClass("hidden");
949                                 $(".reply-text.text", reply).addClass("hidden");
950                                 $(".expand-reply-text", reply).removeClass("hidden");
951                                 $(".shrink-reply-text", reply).addClass("hidden");
952                         } else {
953                                 $(".reply-text.short-text", reply).addClass("hidden");
954                                 $(".reply-text.text", reply).addClass("hidden");
955                                 $(".expand-reply-text", reply).addClass("hidden");
956                                 $(".shrink-reply-text", reply).addClass("hidden");
957                         }
958                         return false;
959                 });
960         });
961
962         /* convert “show more” link into javascript function. */
963         const toggleShowMore = function() {
964                 $(this).click(function() {
965                         $(".reply-text.text", getReplyElement(this)).toggleClass("hidden");
966                         $(".reply-text.short-text", getReplyElement(this)).toggleClass("hidden");
967                         $(".expand-reply-text", getReplyElement(this)).toggleClass("hidden");
968                         $(".shrink-reply-text", getReplyElement(this)).toggleClass("hidden");
969                         return false;
970                 });
971         };
972         $(replyElement).find(".expand-reply-text").each(toggleShowMore);
973         $(replyElement).find(".shrink-reply-text").each(toggleShowMore);
974
975         /* convert trust control buttons to javascript functions. */
976         $(replyElement).find(".reply-trust").submit(function() {
977                 trustSone(getReplyAuthor(this));
978                 return false;
979         });
980         $(replyElement).find(".reply-distrust").submit(function() {
981                 distrustSone(getReplyAuthor(this));
982                 return false;
983         });
984         $(replyElement).find(".reply-untrust").submit(function() {
985                 untrustSone(getReplyAuthor(this));
986                 return false;
987         });
988
989         /* show Sone menu when hovering over the avatar. */
990         $(replyElement).find(".reply-avatar").mouseover(function() {
991                 if (typeof currentSoneMenuTimeoutHandler !== undefined) {
992                         clearTimeout(currentSoneMenuTimeoutHandler);
993                 }
994                 currentSoneMenuId = getPostId(this) + "-" + getReplyId(this);
995                 currentSoneMenuTimeoutHandler = setTimeout(function() {
996                         $(".sone-menu:visible").fadeOut();
997                         $(".sone-reply-menu", replyElement).mouseleave(function() {
998                                 $(this).fadeOut();
999                         }).fadeIn();
1000                 }, 1000);
1001         }).mouseleave(function() {
1002                 if (currentSoneMenuId === getPostId(this) + "-" + getReplyId(this)) {
1003                         clearTimeout(currentSoneMenuTimeoutHandler);
1004                 }
1005         });
1006         (function(replyElement) {
1007                 const soneId = $(".sone-menu-id", replyElement).text();
1008                 $(".sone-menu .follow", replyElement).click(followSone(soneId));
1009                 $(".sone-menu .unfollow", replyElement).click(unfollowSone(soneId));
1010         })(replyElement);
1011 }
1012
1013 /**
1014  * Ajaxifies the given notification by replacing the form with AJAX.
1015  *
1016  * @param notification
1017  *            jQuery object representing the notification.
1018  */
1019 function ajaxifyNotification(notification) {
1020         notification.find("form").submit(function() {
1021                 return false;
1022         });
1023         notification.find("input[name=returnPage]").val($.url.attr("relative"));
1024         if (notification.find(".short-text").length > 0) {
1025                 notification.find(".short-text").removeClass("hidden");
1026                 notification.find(".text").addClass("hidden");
1027         }
1028         notification.find("form.mark-as-read button").click(function() {
1029                 const allIds = $(":input[name=id]", this.form).val().split(" ");
1030                 for (let index = 0; index < allIds.length; index += 16) {
1031                         const ids = allIds.slice(index, index + 16).join(" ");
1032                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": $(":input[name=type]", this.form).val(), "id": ids});
1033                 }
1034         });
1035         notification.find("a[class^='link-']").each(function() {
1036                 const linkElement = $(this);
1037                 if (linkElement.is("[href^='viewPost']")) {
1038                         const id = linkElement.prop("class").substr(5);
1039                         if (hasPost(id)) {
1040                                 linkElement.prop("href", "#post-" + id).addClass("in-page-link");
1041                         }
1042                 }
1043         });
1044         notification.find("form.dismiss button").click(function() {
1045                 ajaxGet("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.prop("id") }, function() {
1046                         /* dismiss in case of error, too. */
1047                         notification.slideUp();
1048                 }, function() {
1049                         /* ignore error. */
1050                 });
1051         });
1052         return notification;
1053 }
1054
1055 /**
1056  * Returns the notification hash. This hash is used in {@link #getStatus()} to
1057  * determine whether the notifications changed and need to be reloaded.
1058  */
1059 function getNotificationHash() {
1060         return sone.find("#notification-area #notification-hash").text();
1061 }
1062
1063 /**
1064  * Sets the notification hash.
1065  *
1066  * @param notificationHash
1067  *            The new notification hash
1068  */
1069 function setNotificationHash(notificationHash) {
1070         sone.find("#notification-area #notification-hash").text(notificationHash);
1071 }
1072
1073 /**
1074  * Retrieves element IDs from notification elements.
1075  *
1076  * @param notification
1077  *            The notification element
1078  * @param selector
1079  *            The selector of the element containing the ID as text
1080  * @returns All extracted IDs
1081  */
1082 function getElementIds(notification, selector) {
1083         const elementIds = [];
1084         $(selector, notification).each(function() {
1085                 elementIds.push($(this).text());
1086         });
1087         return elementIds;
1088 }
1089
1090 /**
1091  * Compares the given notification elements and calls {@link #markSoneAsKnown()}
1092  * for every ID that is contained in the old notification but not in the new.
1093  *
1094  * @param oldNotification
1095  *            The old notification element
1096  * @param newNotification
1097  *            The new notification element
1098  */
1099 function checkForRemovedSones(oldNotification, newNotification) {
1100         if (getNotificationId(oldNotification) !== "new-sone-notification") {
1101                 return;
1102         }
1103         const oldIds = getElementIds(oldNotification, ".new-sone-id");
1104         const newIds = getElementIds(newNotification, ".new-sone-id");
1105         $.each(oldIds, function(index, value) {
1106                 if ($.inArray(value, newIds) === -1) {
1107                         markSoneAsKnown(getSone(value), true);
1108                 }
1109         });
1110 }
1111
1112 /**
1113  * Compares the given notification elements and calls {@link #markPostAsKnown()}
1114  * for every ID that is contained in the old notification but not in the new.
1115  *
1116  * @param oldNotification
1117  *            The old notification element
1118  * @param newNotification
1119  *            The new notification element
1120  */
1121 function checkForRemovedPosts(oldNotification, newNotification) {
1122         if (getNotificationId(oldNotification) !== "new-post-notification") {
1123                 return;
1124         }
1125         const oldIds = getElementIds(oldNotification, ".post-id");
1126         const newIds = getElementIds(newNotification, ".post-id");
1127         $.each(oldIds, function(index, value) {
1128                 if ($.inArray(value, newIds) === -1) {
1129                         markPostAsKnown(getPost(value), true);
1130                 }
1131         });
1132 }
1133
1134 /**
1135  * Compares the given notification elements and calls
1136  * {@link #markReplyAsKnown()} for every ID that is contained in the old
1137  * notification but not in the new.
1138  *
1139  * @param oldNotification
1140  *            The old notification element
1141  * @param newNotification
1142  *            The new notification element
1143  */
1144 function checkForRemovedReplies(oldNotification, newNotification) {
1145         if (getNotificationId(oldNotification) !== "new-reply-notification") {
1146                 return;
1147         }
1148         const oldIds = getElementIds(oldNotification, ".reply-id");
1149         const newIds = getElementIds(newNotification, ".reply-id");
1150         $.each(oldIds, function(index, value) {
1151                 if ($.inArray(value, newIds) === -1) {
1152                         markReplyAsKnown(getReply(value), true);
1153                 }
1154         });
1155 }
1156
1157 function getStatus() {
1158         const parameters = isViewSonePage() ? {"soneIds": getShownSoneId()} : isKnownSonesPage() ? {"soneIds": getShownSoneIds()} : {};
1159         $.extend(parameters, {
1160                 "elements": JSON.stringify($(".linked-element.not-loaded").map(function () {
1161                         return $(this).prop("title");
1162                 }).toArray())
1163         });
1164         ajaxGet("getStatus.ajax", parameters, function(data) {
1165                 if ((data != null) && data.success) {
1166                         /* process Sone information. */
1167                         $.each(data.sones, function(index, value) {
1168                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdatedUnknown ? null : value.lastUpdated, value.lastUpdatedText);
1169                         });
1170                         notLoggedIn = !data.loggedIn;
1171                         if (!notLoggedIn) {
1172                                 showOfflineMarker(!online);
1173                         }
1174                         if (data.notificationHash !== getNotificationHash()) {
1175                                 console.log("Old hash: ", getNotificationHash(), ", new hash: ", data.notificationHash);
1176                                 requestNotifications();
1177                                 /* process new posts. */
1178                                 $.each(data.newPosts, function(index, value) {
1179                                         loadNewPost(value.id, value.sone, value.recipient, value.time);
1180                                 });
1181                                 /* process new replies. */
1182                                 $.each(data.newReplies, function(index, value) {
1183                                         loadNewReply(value.id, value.sone, value.post);
1184                                 });
1185                         }
1186                         if (data.linkedElements) {
1187                                 loadLinkedElements(data.linkedElements)
1188                         }
1189                         /* do it again in 5 seconds. */
1190                         setTimeout(getStatus, 5000);
1191                 } else {
1192                         /* data.success was false, wait 30 seconds. */
1193                         setTimeout(getStatus, 30000);
1194                 }
1195         }, function() {
1196                 statusRequestQueued = false;
1197                 ajaxError();
1198         });
1199 }
1200
1201 function requestNotifications() {
1202         ajaxGet("getNotifications.ajax", {}, function(data) {
1203                 if (data && data.success) {
1204                         /* search for removed notifications. */
1205                         sone.find("#notification-area .notification").each(function() {
1206                                 const notificationId = $(this).prop("id");
1207                                 let foundNotification = false;
1208                                 $.each(data.notifications, function(index, value) {
1209                                         if (value.id === notificationId) {
1210                                                 foundNotification = true;
1211                                                 return false;
1212                                         }
1213                                 });
1214                                 if (!foundNotification) {
1215                                         if (notificationId === "new-sone-notification" && (data.options["ShowNotification/NewSones"] === true)) {
1216                                                 $(".new-sone-id", this).each(function() {
1217                                                         const soneId = $(this).text();
1218                                                         markSoneAsKnown(getSone(soneId), true);
1219                                                 });
1220                                         } else if (notificationId === "new-post-notification" && (data.options["ShowNotification/NewPosts"] === true)) {
1221                                                 $(".post-id", this).each(function() {
1222                                                         const postId = $(this).text();
1223                                                         markPostAsKnown(getPost(postId), true);
1224                                                 });
1225                                         } else if (notificationId === "new-reply-notification" && (data.options["ShowNotification/NewReplies"] === true)) {
1226                                                 $(".reply-id", this).each(function() {
1227                                                         const replyId = $(this).text();
1228                                                         markReplyAsKnown(getReply(replyId), true);
1229                                                 });
1230                                         }
1231                                         $(this).slideUp("normal", function() {
1232                                                 $(this).remove();
1233                                                 /* remove activity when no notifications are visible. */
1234                                                 if (sone.find("#notification-area .notification").length === 0) {
1235                                                         resetActivity();
1236                                                 }
1237                                         });
1238                                 }
1239                         });
1240                         /* process notifications. */
1241                         $.each(data.notifications, function(index, value) {
1242                                 const oldNotification = getNotification(value.id);
1243                                 const notification = ajaxifyNotification(createNotification(value.id, value.lastUpdatedTime, value.text, value.dismissable)).hide();
1244                                 if (oldNotification.length !== 0) {
1245                                         if ((oldNotification.find(".short-text").length > 0) && (notification.find(".short-text").length > 0)) {
1246                                                 const opened = oldNotification.is(":visible") && oldNotification.find(".short-text").hasClass("hidden");
1247                                                 notification.find(".short-text").toggleClass("hidden", opened);
1248                                                 notification.find(".text").toggleClass("hidden", !opened);
1249                                         }
1250                                         checkForRemovedSones(oldNotification, notification);
1251                                         checkForRemovedPosts(oldNotification, notification);
1252                                         checkForRemovedReplies(oldNotification, notification);
1253                                         oldNotification.replaceWith(notification.show());
1254                                 } else {
1255                                         sone.find("#notification-area").append(notification);
1256                                         if (value.id.substring(0, 5) !== "local") {
1257                                                 notification.slideDown();
1258                                                 setActivity();
1259                                         }
1260                                 }
1261                         });
1262                         setNotificationHash(data.notificationHash);
1263                 }
1264         });
1265 }
1266
1267 /**
1268  * Returns the ID of the currently logged in Sone.
1269  *
1270  * @return The ID of the current Sone, or an empty string if no Sone is logged
1271  *         in
1272  */
1273 function getCurrentSoneId() {
1274         return $("#currentSoneId").text();
1275 }
1276
1277 /**
1278  * Returns the content of the page-id attribute.
1279  *
1280  * @returns String The page ID
1281  */
1282 function getPageId() {
1283         return sone.find(".page-id").text();
1284 }
1285
1286 /**
1287  * Returns whether the current page is the index page.
1288  *
1289  * @returns {Boolean} <code>true</code> if the current page is the index page,
1290  *          <code>false</code> otherwise
1291  */
1292 function isIndexPage() {
1293         return getPageId() === "index";
1294 }
1295
1296 /**
1297  * Returns the current page of the selected pagination. If no pagination can be
1298  * found with the given selector, {@code 1} is returned.
1299  *
1300  * @param paginationSelector
1301  *            The pagination selector
1302  * @returns The current page of the pagination
1303  */
1304 function getPage(paginationSelector) {
1305         const pagination = $(paginationSelector);
1306         if (pagination.length > 0) {
1307                 return $(".current-page", paginationSelector).text();
1308         }
1309         return 1;
1310 }
1311
1312 /**
1313  * Returns whether the current page is a “view Sone” page.
1314  *
1315  * @returns {Boolean} <code>true</code> if the current page is a “view Sone”
1316  *          page, <code>false</code> otherwise
1317  */
1318 function isViewSonePage() {
1319         return getPageId() === "view-sone";
1320 }
1321
1322 /**
1323  * Returns the ID of the currently shown Sone. This will only return a sensible
1324  * value if isViewSonePage() returns <code>true</code>.
1325  *
1326  * @returns The ID of the currently shown Sone
1327  */
1328 function getShownSoneId() {
1329         return sone.find(".sone-id").first().text();
1330 }
1331
1332 /**
1333  * Returns the ID of all currently visible Sones. This is mainly used on the
1334  * “Known Sones” page.
1335  *
1336  * @returns The ID of the currently shown Sones
1337  */
1338 function getShownSoneIds() {
1339         const soneIds = [];
1340         sone.find("#known-sones .sone .id").each(function() {
1341                 soneIds.push($(this).text());
1342         });
1343         return soneIds.join(",");
1344 }
1345
1346 /**
1347  * Returns whether the current page is a “view post” page.
1348  *
1349  * @returns {Boolean} <code>true</code> if the current page is a “view post”
1350  *          page, <code>false</code> otherwise
1351  */
1352 function isViewPostPage() {
1353         return getPageId() === "view-post";
1354 }
1355
1356 /**
1357  * Returns the ID of the currently shown post. This will only return a sensible
1358  * value if isViewPostPage() returns <code>true</code>.
1359  *
1360  * @returns The ID of the currently shown post
1361  */
1362 function getShownPostId() {
1363         return sone.find(".post-id").text();
1364 }
1365
1366 /**
1367  * Returns whether the current page is the “known Sones” page.
1368  *
1369  * @returns {Boolean} <code>true</code> if the current page is the “known
1370  *          Sones” page, <code>false</code> otherwise
1371  */
1372 function isKnownSonesPage() {
1373         return getPageId() === "known-sones";
1374 }
1375
1376 /**
1377  * Returns whether a post with the given ID exists on the current page.
1378  *
1379  * @param postId
1380  *            The post ID to check for
1381  * @returns {Boolean} <code>true</code> if a post with the given ID already
1382  *          exists on the page, <code>false</code> otherwise
1383  */
1384 function hasPost(postId) {
1385         return $(".post#post-" + postId).length > 0;
1386 }
1387
1388 /**
1389  * Returns whether a reply with the given ID exists on the current page.
1390  *
1391  * @param replyId
1392  *            The reply ID to check for
1393  * @returns {Boolean} <code>true</code> if a reply with the given ID already
1394  *          exists on the page, <code>false</code> otherwise
1395  */
1396 function hasReply(replyId) {
1397         return sone.find(".reply#reply-" + replyId).length > 0;
1398 }
1399
1400 function loadNewPost(postId, soneId, recipientId, time) {
1401         if (hasPost(postId)) {
1402                 return;
1403         }
1404         if (!isIndexPage() || (getPage(".pagination-index") > 1)) {
1405                 if (!isViewPostPage() || (getShownPostId() !== postId)) {
1406                         if (!isViewSonePage() || ((getShownSoneId() !== soneId) && (getShownSoneId() !== recipientId)) || (getPage(".post-navigation") > 1)) {
1407                                 return;
1408                         }
1409                 }
1410         }
1411         if (getPostTime(sone.find(".post").last()) > time) {
1412                 return;
1413         }
1414         ajaxGet("getPost.ajax", { "post" : postId }, function(data) {
1415                 if ((data != null) && data.success) {
1416                         if (hasPost(data.post.id)) {
1417                                 return;
1418                         }
1419                         if ((!isIndexPage() || (getPage(".pagination-index") > 1)) && !(isViewSonePage() && ((getShownSoneId() === data.post.sone) || (getShownSoneId() === data.post.recipient) || (getPage(".post-navigation") > 1)))) {
1420                                 return;
1421                         }
1422                         let firstOlderPost = null;
1423                         sone.find(".post").each(function() {
1424                                 if (getPostTime(this) < data.post.time) {
1425                                         firstOlderPost = $(this);
1426                                         return false;
1427                                 }
1428                         });
1429                         const newPost = $(data.post.html).addClass("hidden");
1430                         if ($(".post-author-local", newPost).text() === "true") {
1431                                 newPost.removeClass("new");
1432                         }
1433                         if (firstOlderPost != null) {
1434                                 newPost.insertBefore(firstOlderPost);
1435                         }
1436                         ajaxifyPost(newPost);
1437                         updatePostTimes(data.post.id);
1438                         newPost.slideDown();
1439                         setActivity();
1440                 }
1441         });
1442 }
1443
1444 function loadNewReply(replyId, soneId, postId) {
1445         if (hasReply(replyId)) {
1446                 return;
1447         }
1448         if (!hasPost(postId)) {
1449                 return;
1450         }
1451         ajaxGet("getReply.ajax", { "reply": replyId }, function(data) {
1452                 /* find post. */
1453                 if ((data != null) && data.success) {
1454                         if (hasReply(data.reply.id)) {
1455                                 return;
1456                         }
1457                         sone.find(".post#post-" + data.reply.postId).each(function() {
1458                                 let firstNewerReply = null;
1459                                 $(this).find(".replies .reply").each(function() {
1460                                         if (getReplyTime(this) > data.reply.time) {
1461                                                 firstNewerReply = $(this);
1462                                                 return false;
1463                                         }
1464                                 });
1465                                 const newReply = $(data.reply.html).addClass("hidden");
1466                                 if ($(".reply-author-local", newReply).text() === "true") {
1467                                         newReply.removeClass("new");
1468                                         (function(newReply) {
1469                                                 setTimeout(function() {
1470                                                         markReplyAsKnown(newReply, false);
1471                                                 }, 5000);
1472                                         })(newReply);
1473                                 }
1474                                 if (firstNewerReply != null) {
1475                                         newReply.insertBefore(firstNewerReply);
1476                                 } else {
1477                                         if ($(this).find(".replies .create-reply")) {
1478                                                 $(this).find(".replies .create-reply").before(newReply);
1479                                         } else {
1480                                                 $(this).find(".replies").append(newReply);
1481                                         }
1482                                 }
1483                                 ajaxifyReply(newReply);
1484                                 updateReplyTimes(data.reply.id);
1485                                 newReply.slideDown();
1486                                 setActivity();
1487                                 return false;
1488                         });
1489                 }
1490         });
1491 }
1492
1493 function loadLinkedElements(links) {
1494         const failedElements = links.filter(function(element) {
1495                 return element.failed;
1496         });
1497         if (failedElements.length > 0) {
1498                 failedElements.forEach(function(element) {
1499                         getLinkedElements(element.link).each(function() {
1500                                 $(this).remove()
1501                         });
1502                 });
1503         }
1504         const loadedElements = links.filter(function(element) {
1505                 return !element.loading && !element.failed;
1506         });
1507         if (loadedElements.length > 0) {
1508                 ajaxGet("getLinkedElement.ajax", {
1509                         "elements": JSON.stringify(loadedElements.map(function(element) {
1510                                 return element.link;
1511                         }))
1512                 }, function (data) {
1513                         if ((data != null) && (data.success)) {
1514                                 data.linkedElements.forEach(function (linkedElement) {
1515                                         getLinkedElements(linkedElement.link).each(function() {
1516                                                 $(this).replaceWith(linkedElement.html);
1517                                         });
1518                                 });
1519                         }
1520                 });
1521         }
1522 }
1523
1524 function getLinkedElements(link) {
1525         return $(".linked-element[title='" + link + "']")
1526 }
1527
1528 /**
1529  * Marks the given Sone as known if it is still new.
1530  *
1531  * @param soneElement
1532  *            The Sone to mark as known
1533  * @param skipRequest
1534  *            true to skip the JSON request, false or omit to perform the JSON
1535  *            request
1536  */
1537 function markSoneAsKnown(soneElement, skipRequest) {
1538         if ($(soneElement).hasClass("new")) {
1539                 $(soneElement).removeClass("new");
1540                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1541                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "sone", "id": getSoneId(soneElement)});
1542                         requestNotifications();
1543                 }
1544         }
1545 }
1546
1547 function markPostAsKnown(postElements, skipRequest) {
1548         $(postElements).each(function() {
1549                 const postElement = this;
1550                 if ($(postElement).hasClass("new") || ((typeof skipRequest != "undefined"))) {
1551                         (function(postElement) {
1552                                 $(postElement).removeClass("new");
1553                                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1554                                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "post", "id": getPostId(postElement)});
1555                                         requestNotifications();
1556                                 }
1557                         })(postElement);
1558                 }
1559                 $(".click-to-show", postElement).removeClass("new");
1560         });
1561         markReplyAsKnown($(postElements).find(".reply"), true);
1562 }
1563
1564 function markReplyAsKnown(replyElements, skipRequest) {
1565         $(replyElements).each(function() {
1566                 const replyElement = this;
1567                 if ($(replyElement).hasClass("new") || ((typeof skipRequest != "undefined"))) {
1568                         (function(replyElement) {
1569                                 $(replyElement).removeClass("new");
1570                                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1571                                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "reply", "id": getReplyId(replyElement)});
1572                                         requestNotifications();
1573                                 }
1574                         })(replyElement);
1575                 }
1576         });
1577 }
1578
1579 /**
1580  * Updates the time of the post with the given ID.
1581  *
1582  * @param postId
1583  *            The ID of the post to update
1584  * @param timeText
1585  *            The text of the time to show
1586  * @param refreshTime
1587  *            The refresh time after which to request a new time (in seconds)
1588  * @param tooltip
1589  *            The tooltip to show
1590  */
1591 function updatePostTime(postId, timeText, refreshTime, tooltip) {
1592         if (!getPost(postId).is(":visible")) {
1593                 return;
1594         }
1595         getPost(postId).find(".post-status-line > .time a").html(timeText).prop("title", tooltip);
1596         (function(postId, refreshTime) {
1597                 setTimeout(function() {
1598                         updatePostTimes(postId);
1599                 }, refreshTime * 1000);
1600         })(postId, refreshTime);
1601 }
1602
1603 /**
1604  * Requests new rendered times for the posts with the given IDs.
1605  *
1606  * @param postIds
1607  *            Comma-separated post IDs
1608  */
1609 function updatePostTimes(postIds) {
1610         if (postIds !== "") {
1611         ajaxGet("getTimes.ajax", {"posts": postIds}, function (data) {
1612             if ((data != null) && data.success) {
1613                 $.each(data.postTimes, function (index, value) {
1614                     updatePostTime(index, value.timeText, value.refreshTime, value.tooltip);
1615                 });
1616             }
1617         });
1618     }
1619 }
1620
1621 /**
1622  * Updates the time of the reply with the given ID.
1623  *
1624  * @param replyId
1625  *            The ID of the reply to update
1626  * @param timeText
1627  *            The text of the time to show
1628  * @param refreshTime
1629  *            The refresh time after which to request a new time (in seconds)
1630  * @param tooltip
1631  *            The tooltip to show
1632  */
1633 function updateReplyTime(replyId, timeText, refreshTime, tooltip) {
1634         getReply(replyId).find(".reply-status-line > .time").html(timeText).prop("title", tooltip);
1635         (function(replyId, refreshTime) {
1636                 setTimeout(function() {
1637                         updateReplyTimes(replyId);
1638                 }, refreshTime * 1000);
1639         })(replyId, refreshTime);
1640 }
1641
1642 /**
1643  * Requests new rendered times for the posts with the given IDs.
1644  *
1645  * @param replyIds
1646  *            Comma-separated post IDs
1647  */
1648 function updateReplyTimes(replyIds) {
1649         if (replyIds !== "") {
1650         ajaxGet("getTimes.ajax", {"replies": replyIds}, function (data) {
1651             if ((data != null) && data.success) {
1652                 $.each(data.replyTimes, function (index, value) {
1653                     updateReplyTime(index, value.timeText, value.refreshTime, value.tooltip);
1654                 });
1655             }
1656         });
1657     }
1658 }
1659
1660 function resetActivity() {
1661         const title = document.title;
1662         if (title.indexOf('(') === 0) {
1663                 setTitle(title.substr(title.indexOf(' ') + 1));
1664         }
1665         iconBlinking = false;
1666 }
1667
1668 function setActivity() {
1669         if (!focus) {
1670                 const title = document.title;
1671                 if (title.indexOf('(') !== 0) {
1672                         setTitle("(!) " + title);
1673                 }
1674                 if (!iconBlinking) {
1675                         setTimeout(toggleIcon, 1500);
1676                         iconBlinking = true;
1677                 }
1678         }
1679 }
1680
1681 /**
1682  * Sets the window title after a small delay to prevent race-condition issues.
1683  *
1684  * @param title
1685  *            The title to set
1686  */
1687 function setTitle(title) {
1688         setTimeout(function() {
1689                 document.title = title;
1690         }, 50);
1691 }
1692
1693 /** Whether the icon is currently showing activity. */
1694 let iconActive = false;
1695
1696 /** Whether the icon is currently supposed to blink. */
1697 let iconBlinking = false;
1698
1699 /**
1700  * Toggles the icon. If the window has gained focus and the icon is still
1701  * showing the activity state, it is returned to normal.
1702  */
1703 function toggleIcon() {
1704         if (focus || !iconBlinking) {
1705                 if (iconActive) {
1706                         changeIcon("images/icon.png");
1707                         iconActive = false;
1708                 }
1709                 iconBlinking = false;
1710         } else {
1711                 iconActive = !iconActive;
1712                 changeIcon(iconActive ? "images/icon-activity.png" : "images/icon.png");
1713                 setTimeout(toggleIcon, 1500);
1714         }
1715 }
1716
1717 /**
1718  * Changes the icon of the page.
1719  *
1720  * @param iconUrl
1721  *            The new URL of the icon
1722  */
1723 function changeIcon(iconUrl) {
1724         $("link[rel=icon]").remove();
1725         $("head").append($("<link>").prop("rel", "icon").prop("type", "image/png").prop("href", iconUrl));
1726         $("iframe[id=icon-update]")[0].src += "";
1727 }
1728
1729 /**
1730  * Creates a new notification.
1731  *
1732  * @param id
1733  *            The ID of the notificaiton
1734  * @param text
1735  *            The text of the notification
1736  * @param dismissable
1737  *            <code>true</code> if the notification can be dismissed by the
1738  *            user
1739  */
1740 function createNotification(id, lastUpdatedTime, text, dismissable) {
1741         const notification = $("<div></div>").addClass("notification").prop("id", id).prop("lastUpdatedTime", lastUpdatedTime);
1742         if (dismissable) {
1743                 const dismissForm = sone.find("#notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id");
1744                 dismissForm.find("input[name=notification]").val(id);
1745                 notification.append(dismissForm);
1746         }
1747         notification.append(text);
1748         return notification;
1749 }
1750
1751 /**
1752  * Shows the details of the notification with the given ID.
1753  *
1754  * @param notificationId
1755  *            The ID of the notification
1756  */
1757 function showNotificationDetails(notificationId) {
1758         sone.find(".notification#" + notificationId + " .text").removeClass("hidden");
1759         sone.find(".notification#" + notificationId + " .short-text").addClass("hidden");
1760 }
1761
1762 /**
1763  * Deletes the field with the given ID from the profile.
1764  *
1765  * @param fieldId
1766  *            The ID of the field to delete
1767  */
1768 function deleteProfileField(fieldId) {
1769         ajaxGet("deleteProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId}, function(data) {
1770                 if (data && data.success) {
1771                         sone.find(".profile-field#" + data.field.id).slideUp();
1772                 }
1773         });
1774 }
1775
1776 /**
1777  * Renames a profile field.
1778  *
1779  * @param fieldId
1780  *            The ID of the field to rename
1781  * @param newName
1782  *            The new name of the field
1783  * @param successFunction
1784  *            Called when the renaming was successful
1785  */
1786 function editProfileField(fieldId, newName, successFunction) {
1787         ajaxGet("editProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "name": newName}, function(data) {
1788                 if (data && data.success) {
1789                         successFunction();
1790                 }
1791         });
1792 }
1793
1794 /**
1795  * Moves the profile field with the given ID one slot in the given direction.
1796  *
1797  * @param fieldId
1798  *            The ID of the field to move
1799  * @param direction
1800  *            The direction to move in (“up” or “down”)
1801  * @param successFunction
1802  *            Function to call on success
1803  */
1804 function moveProfileField(fieldId, direction, successFunction) {
1805         ajaxGet("moveProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "direction": direction}, function(data) {
1806                 if (data && data.success) {
1807                         successFunction();
1808                 }
1809         });
1810 }
1811
1812 /**
1813  * Moves the profile field with the given ID up one slot.
1814  *
1815  * @param fieldId
1816  *            The ID of the field to move
1817  * @param successFunction
1818  *            Function to call on success
1819  */
1820 function moveProfileFieldUp(fieldId, successFunction) {
1821         moveProfileField(fieldId, "up", successFunction);
1822 }
1823
1824 /**
1825  * Moves the profile field with the given ID down one slot.
1826  *
1827  * @param fieldId
1828  *            The ID of the field to move
1829  * @param successFunction
1830  *            Function to call on success
1831  */
1832 function moveProfileFieldDown(fieldId, successFunction) {
1833         moveProfileField(fieldId, "down", successFunction);
1834 }
1835
1836 let statusRequestQueued = true;
1837
1838 /**
1839  * Sets the status of the web interface as offline.
1840  */
1841 function ajaxError() {
1842         online = false;
1843         showOfflineMarker(true);
1844         if (!statusRequestQueued) {
1845                 setTimeout(getStatus, 5000);
1846                 statusRequestQueued = true;
1847         }
1848 }
1849
1850 /**
1851  * Sets the status of the web interface as online.
1852  */
1853 function ajaxSuccess() {
1854         online = true;
1855         showOfflineMarker(!online || (initiallyLoggedIn && notLoggedIn));
1856 }
1857
1858 /**
1859  * Shows or hides the offline marker.
1860  *
1861  * @param visible
1862  *            {@code true} to display the offline marker, {@code false} to hide
1863  *            it
1864  */
1865 function showOfflineMarker(visible) {
1866         /* jQuery documentation says toggle() works the other way around?! */
1867         sone.find("#offline-marker").toggle(visible);
1868         if (visible) {
1869                 sone.find("#main").addClass("offline");
1870         } else {
1871                 sone.find("#main").removeClass("offline");
1872         }
1873 }
1874
1875 //
1876 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
1877 //
1878
1879 const sone = $("#sone");
1880 let focus = true;
1881 let online = true;
1882 const initiallyLoggedIn = sone.find("#loggedIn").text() === "true";
1883 let notLoggedIn = !initiallyLoggedIn;
1884
1885 /** ID of the next-to-show Sone context menu. */
1886 let currentSoneMenuId;
1887
1888 /** Timeout handler for the next-to-show Sone context menu. */
1889 let currentSoneMenuTimeoutHandler;
1890
1891 $(document).ready(function() {
1892
1893         /* rip out the status update textarea. */
1894         sone.find(".rip-out").each(function() {
1895                 const oldElement = $(this);
1896                 const newElement = $("<input type='text'/>");
1897                 newElement.prop("class", oldElement.prop("class")).prop("name", oldElement.prop("name"));
1898                 oldElement.before(newElement).remove();
1899         });
1900
1901         /* this initializes the status update input field. */
1902         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
1903                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
1904                 sone.find("#update-status .select-sender").css("display", "inline");
1905                 sone.find("#update-status .sender").hide();
1906                 sone.find("#update-status .select-sender button").click(function() {
1907                         sone.find("#update-status .sender").show();
1908                         sone.find("#update-status .select-sender").hide();
1909                         return false;
1910                 });
1911                 sone.find("#update-status").submit(function() {
1912                         const button = $("button:submit", this);
1913                         button.prop("disabled", "disabled");
1914                         if ($(this).find(":input.default:enabled").length > 0) {
1915                                 return false;
1916                         }
1917                         const sender = $(this).find(":input[name=sender]").val();
1918                         const text = $(this).find(":input[name=text]:enabled").val();
1919                         ajaxGet("createPost.ajax", { "formPassword": getFormPassword(), "sender": sender, "text": text }, function() {
1920                                 button.removeAttr("disabled");
1921                         });
1922                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1923                         $(this).find(":input[name=text]:enabled").val("").blur();
1924                         $(this).find(".sender").hide();
1925                         $(this).find(".select-sender").show();
1926                         return false;
1927                 });
1928         });
1929
1930         /* ajaxify the search input field. */
1931         getTranslation("WebInterface.DefaultText.Search", function(defaultText) {
1932                 registerInputTextareaSwap("#sone #search input[name=query]", defaultText, "query", false, true);
1933         });
1934
1935         /* ajaxify input field on “view Sone” page. */
1936         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
1937                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
1938                 sone.find("#post-message .select-sender").css("display", "inline");
1939                 sone.find("#post-message .sender").hide();
1940                 sone.find("#post-message .select-sender button").click(function() {
1941                         sone.find("#post-message .sender").show();
1942                         sone.find("#post-message .select-sender").hide();
1943                         return false;
1944                 });
1945                 sone.find("#post-message").submit(function() {
1946                         const sender = $(this).find(":input[name=sender]").val();
1947                         const text = $(this).find(":input[name=text]:enabled").val();
1948                         ajaxGet("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "sender": sender, "text": text });
1949                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1950                         $(this).find(":input[name=text]:enabled").val("").blur();
1951                         $(this).find(".sender").hide();
1952                         $(this).find(".select-sender").show();
1953                         return false;
1954                 });
1955         });
1956
1957         /* Ajaxifies all posts. */
1958         /* calling getTranslation here will cache the necessary values. */
1959         getTranslation("WebInterface.Confirmation.DeletePostButton", function() {
1960                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function() {
1961                         getTranslation("WebInterface.DefaultText.Reply", function() {
1962                 getTranslation("WebInterface.Button.Comment", function () {
1963                     sone.find(".post").each(function() {
1964                                                 ajaxifyPost(this);
1965                                         });
1966                                 });
1967                         });
1968                 });
1969         });
1970
1971         /* update post times. */
1972         const postIds = [];
1973         sone.find(".post").each(function() {
1974                 postIds.push(getPostId(this));
1975         });
1976         updatePostTimes(postIds.join(","));
1977
1978         /* hides all replies but the latest two. */
1979         if (!isViewPostPage()) {
1980                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
1981                         sone.find(".post .replies").each(function() {
1982                                 const allReplies = $(this).find(".reply");
1983                                 if (allReplies.length > 2) {
1984                                         let newHidden = false;
1985                                         for (let replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1986                                                 $(allReplies[replyIndex]).addClass("hidden");
1987                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1988                                         }
1989                                         const clickToShowElement = $("<div></div>").addClass("click-to-show");
1990                                         if (newHidden) {
1991                                                 clickToShowElement.addClass("new");
1992                                         }
1993                                         (function(clickToShowElement, allReplies, text) {
1994                                                 clickToShowElement.text(text);
1995                                                 clickToShowElement.click(function() {
1996                                                         allReplies.removeClass("hidden");
1997                                                         clickToShowElement.addClass("hidden");
1998                                                 });
1999                                         })(clickToShowElement, allReplies, text);
2000                                         $(allReplies[0]).before(clickToShowElement);
2001                                 }
2002                         });
2003                 });
2004         }
2005
2006         sone.find(".sone").each(function() {
2007                 ajaxifySone($(this));
2008         });
2009
2010         /* process all existing notifications, ajaxify dismiss buttons. */
2011         sone.find("#notification-area .notification").each(function() {
2012                 ajaxifyNotification($(this));
2013         });
2014
2015         /* activate status polling. */
2016         setTimeout(getStatus, 5000);
2017
2018         /* reset activity counter when the page has focus. */
2019         $(window).focus(function() {
2020                 focus = true;
2021                 resetActivity();
2022         }).blur(function() {
2023                 focus = false;
2024         });
2025
2026 });