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