🔀 Merge branch 'release/v82'
[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 function getStatus() {
1062         const parameters = isViewSonePage() ? {"soneIds": getShownSoneId()} : isKnownSonesPage() ? {"soneIds": getShownSoneIds()} : {};
1063         $.extend(parameters, {
1064                 "elements": JSON.stringify($(".linked-element.not-loaded").map(function () {
1065                         return $(this).prop("title");
1066                 }).toArray())
1067         });
1068         ajaxGet("getStatus.ajax", parameters, function(data) {
1069                 if ((data != null) && data.success) {
1070                         /* process Sone information. */
1071                         $.each(data.sones, function(index, value) {
1072                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdatedUnknown ? null : value.lastUpdated, value.lastUpdatedText);
1073                         });
1074                         notLoggedIn = !data.loggedIn;
1075                         if (!notLoggedIn) {
1076                                 showOfflineMarker(!online);
1077                         }
1078                         if (data.notificationHash !== getNotificationHash()) {
1079                                 console.log("Old hash: ", getNotificationHash(), ", new hash: ", data.notificationHash);
1080                                 requestNotifications();
1081                                 /* process new posts. */
1082                                 $.each(data.newPosts, function(index, value) {
1083                                         loadNewPost(value.id, value.sone, value.recipient, value.time);
1084                                 });
1085                                 /* process new replies. */
1086                                 $.each(data.newReplies, function(index, value) {
1087                                         loadNewReply(value.id, value.sone, value.post);
1088                                 });
1089                         }
1090                         if (data.linkedElements) {
1091                                 loadLinkedElements(data.linkedElements)
1092                         }
1093                         /* do it again in 5 seconds. */
1094                         setTimeout(getStatus, 5000);
1095                 } else {
1096                         /* data.success was false, wait 30 seconds. */
1097                         setTimeout(getStatus, 30000);
1098                 }
1099         }, function() {
1100                 statusRequestQueued = false;
1101                 ajaxError();
1102         });
1103 }
1104
1105 function requestNotifications() {
1106         ajaxGet("getNotifications.ajax", {}, function(data) {
1107                 if (data && data.success) {
1108                         /* search for removed notifications. */
1109                         sone.find("#notification-area .notification").each(function() {
1110                                 const notificationId = $(this).prop("id");
1111                                 let foundNotification = false;
1112                                 $.each(data.notifications, function(index, value) {
1113                                         if (value.id === notificationId) {
1114                                                 foundNotification = true;
1115                                                 return false;
1116                                         }
1117                                 });
1118                                 if (!foundNotification) {
1119                                         if (notificationId === "new-sone-notification" && (data.options["ShowNotification/NewSones"] === true)) {
1120                                                 $(".new-sone-id", this).each(function() {
1121                                                         const soneId = $(this).text();
1122                                                         markSoneAsKnown(getSone(soneId), true);
1123                                                 });
1124                                         } else if (notificationId === "new-post-notification" && (data.options["ShowNotification/NewPosts"] === true)) {
1125                                                 $(".post-id", this).each(function() {
1126                                                         const postId = $(this).text();
1127                                                         markPostAsKnown(getPost(postId), true);
1128                                                 });
1129                                         } else if (notificationId === "new-reply-notification" && (data.options["ShowNotification/NewReplies"] === true)) {
1130                                                 $(".reply-id", this).each(function() {
1131                                                         const replyId = $(this).text();
1132                                                         markReplyAsKnown(getReply(replyId), true);
1133                                                 });
1134                                         }
1135                                         $(this).slideUp("normal", function() {
1136                                                 $(this).remove();
1137                                                 /* remove activity when no notifications are visible. */
1138                                                 if (sone.find("#notification-area .notification").length === 0) {
1139                                                         resetActivity();
1140                                                 }
1141                                         });
1142                                 }
1143                         });
1144                         /* process notifications. */
1145                         $.each(data.notifications, function(index, value) {
1146                                 const oldNotification = getNotification(value.id);
1147                                 const notification = ajaxifyNotification(createNotification(value.id, value.lastUpdatedTime, value.text, value.dismissable)).hide();
1148                                 if (oldNotification.length !== 0) {
1149                                         if ((oldNotification.find(".short-text").length > 0) && (notification.find(".short-text").length > 0)) {
1150                                                 const opened = oldNotification.is(":visible") && oldNotification.find(".short-text").hasClass("hidden");
1151                                                 notification.find(".short-text").toggleClass("hidden", opened);
1152                                                 notification.find(".text").toggleClass("hidden", !opened);
1153                                         }
1154                                         checkForRemovedSones(oldNotification, notification);
1155                                         checkForRemovedPosts(oldNotification, notification);
1156                                         checkForRemovedReplies(oldNotification, notification);
1157                                         oldNotification.replaceWith(notification.show());
1158                                 } else {
1159                                         sone.find("#notification-area").append(notification);
1160                                         if (value.id.substring(0, 5) !== "local") {
1161                                                 notification.slideDown();
1162                                                 setActivity();
1163                                         }
1164                                 }
1165                         });
1166                         setNotificationHash(data.notificationHash);
1167                 }
1168         });
1169 }
1170
1171 /**
1172  * Returns the ID of the currently logged in Sone.
1173  *
1174  * @return The ID of the current Sone, or an empty string if no Sone is logged
1175  *         in
1176  */
1177 function getCurrentSoneId() {
1178         return $("#currentSoneId").text();
1179 }
1180
1181 /**
1182  * Returns the content of the page-id attribute.
1183  *
1184  * @returns String The page ID
1185  */
1186 function getPageId() {
1187         return sone.find(".page-id").text();
1188 }
1189
1190 /**
1191  * Returns whether the current page is the index page.
1192  *
1193  * @returns {Boolean} <code>true</code> if the current page is the index page,
1194  *          <code>false</code> otherwise
1195  */
1196 function isIndexPage() {
1197         return getPageId() === "index";
1198 }
1199
1200 /**
1201  * Returns the current page of the selected pagination. If no pagination can be
1202  * found with the given selector, {@code 1} is returned.
1203  *
1204  * @param paginationSelector
1205  *            The pagination selector
1206  * @returns The current page of the pagination
1207  */
1208 function getPage(paginationSelector) {
1209         const pagination = $(paginationSelector);
1210         if (pagination.length > 0) {
1211                 return $(".current-page", paginationSelector).text();
1212         }
1213         return 1;
1214 }
1215
1216 /**
1217  * Returns whether the current page is a â€śview Sone” page.
1218  *
1219  * @returns {Boolean} <code>true</code> if the current page is a â€śview Sone”
1220  *          page, <code>false</code> otherwise
1221  */
1222 function isViewSonePage() {
1223         return getPageId() === "view-sone";
1224 }
1225
1226 /**
1227  * Returns the ID of the currently shown Sone. This will only return a sensible
1228  * value if isViewSonePage() returns <code>true</code>.
1229  *
1230  * @returns The ID of the currently shown Sone
1231  */
1232 function getShownSoneId() {
1233         return sone.find(".sone-id").first().text();
1234 }
1235
1236 /**
1237  * Returns the ID of all currently visible Sones. This is mainly used on the
1238  * â€śKnown Sones” page.
1239  *
1240  * @returns The ID of the currently shown Sones
1241  */
1242 function getShownSoneIds() {
1243         const soneIds = [];
1244         sone.find("#known-sones .sone .id").each(function() {
1245                 soneIds.push($(this).text());
1246         });
1247         return soneIds.join(",");
1248 }
1249
1250 /**
1251  * Returns whether the current page is a â€śview post” page.
1252  *
1253  * @returns {Boolean} <code>true</code> if the current page is a â€śview post”
1254  *          page, <code>false</code> otherwise
1255  */
1256 function isViewPostPage() {
1257         return getPageId() === "view-post";
1258 }
1259
1260 /**
1261  * Returns the ID of the currently shown post. This will only return a sensible
1262  * value if isViewPostPage() returns <code>true</code>.
1263  *
1264  * @returns The ID of the currently shown post
1265  */
1266 function getShownPostId() {
1267         return sone.find(".post-id").text();
1268 }
1269
1270 /**
1271  * Returns whether the current page is the â€śknown Sones” page.
1272  *
1273  * @returns {Boolean} <code>true</code> if the current page is the â€śknown
1274  *          Sones” page, <code>false</code> otherwise
1275  */
1276 function isKnownSonesPage() {
1277         return getPageId() === "known-sones";
1278 }
1279
1280 /**
1281  * Returns whether a post with the given ID exists on the current page.
1282  *
1283  * @param postId
1284  *            The post ID to check for
1285  * @returns {Boolean} <code>true</code> if a post with the given ID already
1286  *          exists on the page, <code>false</code> otherwise
1287  */
1288 function hasPost(postId) {
1289         return $(".post#post-" + postId).length > 0;
1290 }
1291
1292 /**
1293  * Returns whether a reply with the given ID exists on the current page.
1294  *
1295  * @param replyId
1296  *            The reply ID to check for
1297  * @returns {Boolean} <code>true</code> if a reply with the given ID already
1298  *          exists on the page, <code>false</code> otherwise
1299  */
1300 function hasReply(replyId) {
1301         return sone.find(".reply#reply-" + replyId).length > 0;
1302 }
1303
1304 function loadNewPost(postId, soneId, recipientId, time) {
1305         if (hasPost(postId)) {
1306                 return;
1307         }
1308         if (!isIndexPage() || (getPage(".pagination-index") > 1)) {
1309                 if (!isViewPostPage() || (getShownPostId() !== postId)) {
1310                         if (!isViewSonePage() || ((getShownSoneId() !== soneId) && (getShownSoneId() !== recipientId)) || (getPage(".post-navigation") > 1)) {
1311                                 return;
1312                         }
1313                 }
1314         }
1315         if (getPostTime(sone.find(".post").last()) > time) {
1316                 return;
1317         }
1318         ajaxGet("getPost.ajax", { "post" : postId }, function(data) {
1319                 if ((data != null) && data.success) {
1320                         if (hasPost(data.post.id)) {
1321                                 return;
1322                         }
1323                         if ((!isIndexPage() || (getPage(".pagination-index") > 1)) && !(isViewSonePage() && ((getShownSoneId() === data.post.sone) || (getShownSoneId() === data.post.recipient) || (getPage(".post-navigation") > 1)))) {
1324                                 return;
1325                         }
1326                         let firstOlderPost = null;
1327                         sone.find(".post").each(function() {
1328                                 if (getPostTime(this) < data.post.time) {
1329                                         firstOlderPost = $(this);
1330                                         return false;
1331                                 }
1332                         });
1333                         const newPost = $(data.post.html).addClass("hidden");
1334                         if ($(".post-author-local", newPost).text() === "true") {
1335                                 newPost.removeClass("new");
1336                         }
1337                         if (firstOlderPost != null) {
1338                                 newPost.insertBefore(firstOlderPost);
1339                         }
1340                         ajaxifyPost(newPost);
1341                         updatePostTimes(data.post.id);
1342                         newPost.slideDown();
1343                         setActivity();
1344                 }
1345         });
1346 }
1347
1348 function loadNewReply(replyId, soneId, postId) {
1349         if (hasReply(replyId)) {
1350                 return;
1351         }
1352         if (!hasPost(postId)) {
1353                 return;
1354         }
1355         ajaxGet("getReply.ajax", { "reply": replyId }, function(data) {
1356                 /* find post. */
1357                 if ((data != null) && data.success) {
1358                         if (hasReply(data.reply.id)) {
1359                                 return;
1360                         }
1361                         sone.find(".post#post-" + data.reply.postId).each(function() {
1362                                 let firstNewerReply = null;
1363                                 $(this).find(".replies .reply").each(function() {
1364                                         if (getReplyTime(this) > data.reply.time) {
1365                                                 firstNewerReply = $(this);
1366                                                 return false;
1367                                         }
1368                                 });
1369                                 const newReply = $(data.reply.html).addClass("hidden");
1370                                 if ($(".reply-author-local", newReply).text() === "true") {
1371                                         newReply.removeClass("new");
1372                                         (function(newReply) {
1373                                                 setTimeout(function() {
1374                                                         markReplyAsKnown(newReply, false);
1375                                                 }, 5000);
1376                                         })(newReply);
1377                                 }
1378                                 if (firstNewerReply != null) {
1379                                         newReply.insertBefore(firstNewerReply);
1380                                 } else {
1381                                         if ($(this).find(".replies .create-reply")) {
1382                                                 $(this).find(".replies .create-reply").before(newReply);
1383                                         } else {
1384                                                 $(this).find(".replies").append(newReply);
1385                                         }
1386                                 }
1387                                 ajaxifyReply(newReply);
1388                                 updateReplyTimes(data.reply.id);
1389                                 newReply.slideDown();
1390                                 setActivity();
1391                                 return false;
1392                         });
1393                 }
1394         });
1395 }
1396
1397 function loadLinkedElements(links) {
1398         const failedElements = links.filter(function(element) {
1399                 return element.failed;
1400         });
1401         if (failedElements.length > 0) {
1402                 failedElements.forEach(function(element) {
1403                         getLinkedElements(element.link).each(function() {
1404                                 $(this).remove()
1405                         });
1406                 });
1407         }
1408         const loadedElements = links.filter(function(element) {
1409                 return !element.loading && !element.failed;
1410         });
1411         if (loadedElements.length > 0) {
1412                 ajaxGet("getLinkedElement.ajax", {
1413                         "elements": JSON.stringify(loadedElements.map(function(element) {
1414                                 return element.link;
1415                         }))
1416                 }, function (data) {
1417                         if ((data != null) && (data.success)) {
1418                                 data.linkedElements.forEach(function (linkedElement) {
1419                                         getLinkedElements(linkedElement.link).each(function() {
1420                                                 $(this).replaceWith(linkedElement.html);
1421                                         });
1422                                 });
1423                         }
1424                 });
1425         }
1426 }
1427
1428 function getLinkedElements(link) {
1429         return $(".linked-element[title='" + link + "']")
1430 }
1431
1432 /**
1433  * Marks the given Sone as known if it is still new.
1434  *
1435  * @param soneElement
1436  *            The Sone to mark as known
1437  * @param skipRequest
1438  *            true to skip the JSON request, false or omit to perform the JSON
1439  *            request
1440  */
1441 function markSoneAsKnown(soneElement, skipRequest) {
1442         if ($(soneElement).hasClass("new")) {
1443                 $(soneElement).removeClass("new");
1444                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1445                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "sone", "id": getSoneId(soneElement)});
1446                         requestNotifications();
1447                 }
1448         }
1449 }
1450
1451 function markPostAsKnown(postElements, skipRequest) {
1452         $(postElements).each(function() {
1453                 const postElement = this;
1454                 if ($(postElement).hasClass("new") || ((typeof skipRequest != "undefined"))) {
1455                         (function(postElement) {
1456                                 $(postElement).removeClass("new");
1457                                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1458                                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "post", "id": getPostId(postElement)});
1459                                         requestNotifications();
1460                                 }
1461                         })(postElement);
1462                 }
1463                 $(".click-to-show", postElement).removeClass("new");
1464         });
1465         markReplyAsKnown($(postElements).find(".reply"), true);
1466 }
1467
1468 function markReplyAsKnown(replyElements, skipRequest) {
1469         $(replyElements).each(function() {
1470                 const replyElement = this;
1471                 if ($(replyElement).hasClass("new") || ((typeof skipRequest != "undefined"))) {
1472                         (function(replyElement) {
1473                                 $(replyElement).removeClass("new");
1474                                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1475                                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "reply", "id": getReplyId(replyElement)});
1476                                         requestNotifications();
1477                                 }
1478                         })(replyElement);
1479                 }
1480         });
1481 }
1482
1483 /**
1484  * Updates the time of the post with the given ID.
1485  *
1486  * @param postId
1487  *            The ID of the post to update
1488  * @param timeText
1489  *            The text of the time to show
1490  * @param refreshTime
1491  *            The refresh time after which to request a new time (in seconds)
1492  * @param tooltip
1493  *            The tooltip to show
1494  */
1495 function updatePostTime(postId, timeText, refreshTime, tooltip) {
1496         if (!getPost(postId).is(":visible")) {
1497                 return;
1498         }
1499         getPost(postId).find(".post-status-line > .time a").html(timeText).prop("title", tooltip);
1500         (function(postId, refreshTime) {
1501                 setTimeout(function() {
1502                         updatePostTimes(postId);
1503                 }, refreshTime * 1000);
1504         })(postId, refreshTime);
1505 }
1506
1507 /**
1508  * Requests new rendered times for the posts with the given IDs.
1509  *
1510  * @param postIds
1511  *            Comma-separated post IDs
1512  */
1513 function updatePostTimes(postIds) {
1514         if (postIds !== "") {
1515         ajaxGet("getTimes.ajax", {"posts": postIds}, function (data) {
1516             if ((data != null) && data.success) {
1517                 $.each(data.postTimes, function (index, value) {
1518                     updatePostTime(index, value.timeText, value.refreshTime, value.tooltip);
1519                 });
1520             }
1521         });
1522     }
1523 }
1524
1525 /**
1526  * Updates the time of the reply with the given ID.
1527  *
1528  * @param replyId
1529  *            The ID of the reply to update
1530  * @param timeText
1531  *            The text of the time to show
1532  * @param refreshTime
1533  *            The refresh time after which to request a new time (in seconds)
1534  * @param tooltip
1535  *            The tooltip to show
1536  */
1537 function updateReplyTime(replyId, timeText, refreshTime, tooltip) {
1538         getReply(replyId).find(".reply-status-line > .time").html(timeText).prop("title", tooltip);
1539         (function(replyId, refreshTime) {
1540                 setTimeout(function() {
1541                         updateReplyTimes(replyId);
1542                 }, refreshTime * 1000);
1543         })(replyId, refreshTime);
1544 }
1545
1546 /**
1547  * Requests new rendered times for the posts with the given IDs.
1548  *
1549  * @param replyIds
1550  *            Comma-separated post IDs
1551  */
1552 function updateReplyTimes(replyIds) {
1553         if (replyIds !== "") {
1554         ajaxGet("getTimes.ajax", {"replies": replyIds}, function (data) {
1555             if ((data != null) && data.success) {
1556                 $.each(data.replyTimes, function (index, value) {
1557                     updateReplyTime(index, value.timeText, value.refreshTime, value.tooltip);
1558                 });
1559             }
1560         });
1561     }
1562 }
1563
1564 function resetActivity() {
1565         const title = document.title;
1566         if (title.indexOf('(') === 0) {
1567                 setTitle(title.substr(title.indexOf(' ') + 1));
1568         }
1569         iconBlinking = false;
1570 }
1571
1572 function setActivity() {
1573         if (!focus) {
1574                 const title = document.title;
1575                 if (title.indexOf('(') !== 0) {
1576                         setTitle("(!) " + title);
1577                 }
1578                 if (!iconBlinking) {
1579                         setTimeout(toggleIcon, 1500);
1580                         iconBlinking = true;
1581                 }
1582         }
1583 }
1584
1585 /**
1586  * Sets the window title after a small delay to prevent race-condition issues.
1587  *
1588  * @param title
1589  *            The title to set
1590  */
1591 function setTitle(title) {
1592         setTimeout(function() {
1593                 document.title = title;
1594         }, 50);
1595 }
1596
1597 /** Whether the icon is currently showing activity. */
1598 let iconActive = false;
1599
1600 /** Whether the icon is currently supposed to blink. */
1601 let iconBlinking = false;
1602
1603 /**
1604  * Toggles the icon. If the window has gained focus and the icon is still
1605  * showing the activity state, it is returned to normal.
1606  */
1607 function toggleIcon() {
1608         if (focus || !iconBlinking) {
1609                 if (iconActive) {
1610                         changeIcon("images/icon.png");
1611                         iconActive = false;
1612                 }
1613                 iconBlinking = false;
1614         } else {
1615                 iconActive = !iconActive;
1616                 changeIcon(iconActive ? "images/icon-activity.png" : "images/icon.png");
1617                 setTimeout(toggleIcon, 1500);
1618         }
1619 }
1620
1621 /**
1622  * Changes the icon of the page.
1623  *
1624  * @param iconUrl
1625  *            The new URL of the icon
1626  */
1627 function changeIcon(iconUrl) {
1628         $("link[rel=icon]").remove();
1629         $("head").append($("<link>").prop("rel", "icon").prop("type", "image/png").prop("href", iconUrl));
1630         $("iframe[id=icon-update]")[0].src += "";
1631 }
1632
1633 /**
1634  * Creates a new notification.
1635  *
1636  * @param id
1637  *            The ID of the notificaiton
1638  * @param text
1639  *            The text of the notification
1640  * @param dismissable
1641  *            <code>true</code> if the notification can be dismissed by the
1642  *            user
1643  */
1644 function createNotification(id, lastUpdatedTime, text, dismissable) {
1645         const notification = $("<div></div>").addClass("notification").prop("id", id).prop("lastUpdatedTime", lastUpdatedTime);
1646         if (dismissable) {
1647                 const dismissForm = sone.find("#notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id");
1648                 dismissForm.find("input[name=notification]").val(id);
1649                 notification.append(dismissForm);
1650         }
1651         notification.append(text);
1652         return notification;
1653 }
1654
1655 /**
1656  * Shows the details of the notification with the given ID.
1657  *
1658  * @param notificationId
1659  *            The ID of the notification
1660  */
1661 function showNotificationDetails(notificationId) {
1662         sone.find(".notification#" + notificationId + " .text").removeClass("hidden");
1663         sone.find(".notification#" + notificationId + " .short-text").addClass("hidden");
1664 }
1665
1666 /**
1667  * Deletes the field with the given ID from the profile.
1668  *
1669  * @param fieldId
1670  *            The ID of the field to delete
1671  */
1672 function deleteProfileField(fieldId) {
1673         ajaxGet("deleteProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId}, function(data) {
1674                 if (data && data.success) {
1675                         sone.find(".profile-field#" + data.field.id).slideUp();
1676                 }
1677         });
1678 }
1679
1680 /**
1681  * Renames a profile field.
1682  *
1683  * @param fieldId
1684  *            The ID of the field to rename
1685  * @param newName
1686  *            The new name of the field
1687  * @param successFunction
1688  *            Called when the renaming was successful
1689  */
1690 function editProfileField(fieldId, newName, successFunction) {
1691         ajaxGet("editProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "name": newName}, function(data) {
1692                 if (data && data.success) {
1693                         successFunction();
1694                 }
1695         });
1696 }
1697
1698 /**
1699  * Moves the profile field with the given ID one slot in the given direction.
1700  *
1701  * @param fieldId
1702  *            The ID of the field to move
1703  * @param direction
1704  *            The direction to move in (“up” or â€śdown”)
1705  * @param successFunction
1706  *            Function to call on success
1707  */
1708 function moveProfileField(fieldId, direction, successFunction) {
1709         ajaxGet("moveProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "direction": direction}, function(data) {
1710                 if (data && data.success) {
1711                         successFunction();
1712                 }
1713         });
1714 }
1715
1716 /**
1717  * Moves the profile field with the given ID up one slot.
1718  *
1719  * @param fieldId
1720  *            The ID of the field to move
1721  * @param successFunction
1722  *            Function to call on success
1723  */
1724 function moveProfileFieldUp(fieldId, successFunction) {
1725         moveProfileField(fieldId, "up", successFunction);
1726 }
1727
1728 /**
1729  * Moves the profile field with the given ID down one slot.
1730  *
1731  * @param fieldId
1732  *            The ID of the field to move
1733  * @param successFunction
1734  *            Function to call on success
1735  */
1736 function moveProfileFieldDown(fieldId, successFunction) {
1737         moveProfileField(fieldId, "down", successFunction);
1738 }
1739
1740 let statusRequestQueued = true;
1741
1742 /**
1743  * Sets the status of the web interface as offline.
1744  */
1745 function ajaxError() {
1746         online = false;
1747         showOfflineMarker(true);
1748         if (!statusRequestQueued) {
1749                 setTimeout(getStatus, 5000);
1750                 statusRequestQueued = true;
1751         }
1752 }
1753
1754 /**
1755  * Sets the status of the web interface as online.
1756  */
1757 function ajaxSuccess() {
1758         online = true;
1759         showOfflineMarker(!online || (initiallyLoggedIn && notLoggedIn));
1760 }
1761
1762 /**
1763  * Shows or hides the offline marker.
1764  *
1765  * @param visible
1766  *            {@code true} to display the offline marker, {@code false} to hide
1767  *            it
1768  */
1769 function showOfflineMarker(visible) {
1770         /* jQuery documentation says toggle() works the other way around?! */
1771         sone.find("#offline-marker").toggle(visible);
1772         if (visible) {
1773                 sone.find("#main").addClass("offline");
1774         } else {
1775                 sone.find("#main").removeClass("offline");
1776         }
1777 }
1778
1779 //
1780 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
1781 //
1782
1783 const sone = $("#sone");
1784 let focus = true;
1785 let online = true;
1786 const initiallyLoggedIn = sone.find("#loggedIn").text() === "true";
1787 let notLoggedIn = !initiallyLoggedIn;
1788
1789 /** ID of the next-to-show Sone context menu. */
1790 let currentSoneMenuId;
1791
1792 /** Timeout handler for the next-to-show Sone context menu. */
1793 let currentSoneMenuTimeoutHandler;
1794
1795 $(document).ready(function() {
1796
1797         /* rip out the status update textarea. */
1798         sone.find(".rip-out").each(function() {
1799                 const oldElement = $(this);
1800                 const newElement = $("<input type='text'/>");
1801                 newElement.prop("class", oldElement.prop("class")).prop("name", oldElement.prop("name"));
1802                 oldElement.before(newElement).remove();
1803         });
1804
1805         /* this initializes the status update input field. */
1806         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
1807                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
1808                 sone.find("#update-status .select-sender").css("display", "inline");
1809                 sone.find("#update-status .sender").hide();
1810                 sone.find("#update-status .select-sender button").click(function() {
1811                         sone.find("#update-status .sender").show();
1812                         sone.find("#update-status .select-sender").hide();
1813                         return false;
1814                 });
1815                 sone.find("#update-status").submit(function() {
1816                         const button = $("button:submit", this);
1817                         button.prop("disabled", "disabled");
1818                         if ($(this).find(":input.default:enabled").length > 0) {
1819                                 return false;
1820                         }
1821                         const sender = $(this).find(":input[name=sender]").val();
1822                         const text = $(this).find(":input[name=text]:enabled").val();
1823                         ajaxGet("createPost.ajax", { "formPassword": getFormPassword(), "sender": sender, "text": text }, function() {
1824                                 button.removeAttr("disabled");
1825                         });
1826                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1827                         $(this).find(":input[name=text]:enabled").val("").blur();
1828                         $(this).find(".sender").hide();
1829                         $(this).find(".select-sender").show();
1830                         return false;
1831                 });
1832         });
1833
1834         /* ajaxify the search input field. */
1835         getTranslation("WebInterface.DefaultText.Search", function(defaultText) {
1836                 registerInputTextareaSwap("#sone #search input[name=query]", defaultText, "query", false, true);
1837         });
1838
1839         /* ajaxify input field on â€śview Sone” page. */
1840         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
1841                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
1842                 sone.find("#post-message .select-sender").css("display", "inline");
1843                 sone.find("#post-message .sender").hide();
1844                 sone.find("#post-message .select-sender button").click(function() {
1845                         sone.find("#post-message .sender").show();
1846                         sone.find("#post-message .select-sender").hide();
1847                         return false;
1848                 });
1849                 sone.find("#post-message").submit(function() {
1850                         const sender = $(this).find(":input[name=sender]").val();
1851                         const text = $(this).find(":input[name=text]:enabled").val();
1852                         ajaxGet("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "sender": sender, "text": text });
1853                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1854                         $(this).find(":input[name=text]:enabled").val("").blur();
1855                         $(this).find(".sender").hide();
1856                         $(this).find(".select-sender").show();
1857                         return false;
1858                 });
1859         });
1860
1861         /* Ajaxifies all posts. */
1862         /* calling getTranslation here will cache the necessary values. */
1863         getTranslation("WebInterface.Confirmation.DeletePostButton", function() {
1864                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function() {
1865                         getTranslation("WebInterface.DefaultText.Reply", function() {
1866                 getTranslation("WebInterface.Button.Comment", function () {
1867                     sone.find(".post").each(function() {
1868                                                 ajaxifyPost(this);
1869                                         });
1870                                 });
1871                         });
1872                 });
1873         });
1874
1875         /* update post times. */
1876         const postIds = [];
1877         sone.find(".post").each(function() {
1878                 postIds.push(getPostId(this));
1879         });
1880         updatePostTimes(postIds.join(","));
1881
1882         /* hides all replies but the latest two. */
1883         if (!isViewPostPage()) {
1884                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
1885                         sone.find(".post .replies").each(function() {
1886                                 const allReplies = $(this).find(".reply");
1887                                 if (allReplies.length > 2) {
1888                                         let newHidden = false;
1889                                         for (let replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1890                                                 $(allReplies[replyIndex]).addClass("hidden");
1891                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1892                                         }
1893                                         const clickToShowElement = $("<div></div>").addClass("click-to-show");
1894                                         if (newHidden) {
1895                                                 clickToShowElement.addClass("new");
1896                                         }
1897                                         (function(clickToShowElement, allReplies, text) {
1898                                                 clickToShowElement.text(text);
1899                                                 clickToShowElement.click(function() {
1900                                                         allReplies.removeClass("hidden");
1901                                                         clickToShowElement.addClass("hidden");
1902                                                 });
1903                                         })(clickToShowElement, allReplies, text);
1904                                         $(allReplies[0]).before(clickToShowElement);
1905                                 }
1906                         });
1907                 });
1908         }
1909
1910         sone.find(".sone").each(function() {
1911                 ajaxifySone($(this));
1912         });
1913
1914         /* process all existing notifications, ajaxify dismiss buttons. */
1915         sone.find("#notification-area .notification").each(function() {
1916                 ajaxifyNotification($(this));
1917         });
1918
1919         /* activate status polling. */
1920         setTimeout(getStatus, 5000);
1921
1922         /* reset activity counter when the page has focus. */
1923         $(window).focus(function() {
1924                 focus = true;
1925                 resetActivity();
1926         }).blur(function() {
1927                 focus = false;
1928         });
1929
1930 });