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