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