f872daeaa916bcb0151c3d815f0217fb9d55ff18
[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 (typeof errorCallback != "undefined") {
12                                 errorCallback();
13                         } else {
14                                 ajaxError();
15                         }
16                 }});
17         })(url, data, successCallback, errorCallback);
18 }
19
20 function ajaxPost(url, data, successCallback, errorCallback) {
21         (function(url, data, successCallback, errorCallback) {
22                 $.ajax({"type": "POST", "url": url, "data": data, "dataType": "json", "success": function(data, textStatus, xmlHttpRequest) {
23                         ajaxSuccess();
24                         if (typeof successCallback != "undefined") {
25                                 successCallback(data, textStatus);
26                         }
27                 }, "error": function(xmlHttpRequest, textStatus, errorThrown) {
28                         if (typeof errorCallback != "undefined") {
29                                 errorCallback();
30                         } else {
31                                 ajaxError();
32                         }
33                 }});
34         })(url, data, successCallback, errorCallback);
35 }
36
37 function registerInputTextareaSwap(inputElement, defaultText, inputFieldName, optional, dontUseTextarea) {
38         $(inputElement).each(function() {
39                 textarea = $(dontUseTextarea ? "<input type=\"text\" name=\"" + inputFieldName + "\">" : "<textarea name=\"" + inputFieldName + "\"></textarea>").blur(function() {
40                         if ($(this).val() == "") {
41                                 $(this).hide();
42                                 inputField = $(this).data("inputField");
43                                 inputField.show().removeAttr("disabled").addClass("default");
44                                 inputField.val(defaultText);
45                         }
46                 }).hide().data("inputField", $(this)).val($(this).val());
47                 $(this).data("textarea", textarea).after(textarea);
48                 (function(inputField, textarea) {
49                         inputField.focus(function() {
50                                 $(this).hide().attr("disabled", "disabled");
51                                 /* no, show(), “display: block” is not what I need. */
52                                 textarea.attr("style", "display: inline").focus();
53                         });
54                         if (inputField.val() == "") {
55                                 inputField.addClass("default");
56                                 inputField.val(defaultText);
57                         } else {
58                                 inputField.hide().attr("disabled", "disabled");
59                                 textarea.show();
60                         }
61                         $(inputField.get(0).form).submit(function() {
62                                 inputField.attr("disabled", "disabled");
63                                 if (!optional && (textarea.val() == "")) {
64                                         inputField.removeAttr("disabled").focus();
65                                         return false;
66                                 }
67                         });
68                 })($(this), textarea);
69         });
70 }
71
72 /**
73  * Adds a “comment” link to all status lines contained in the given element.
74  *
75  * @param postId
76  *            The ID of the post
77  * @param element
78  *            The element to add a “comment” link to
79  */
80 function addCommentLink(postId, author, element, insertAfterThisElement) {
81         if (($(element).find(".show-reply-form").length > 0) || (getPostElement(element).find(".create-reply").length == 0)) {
82                 return;
83         }
84         commentElement = (function(postId, author) {
85                 separator = $("<span> · </span>").addClass("separator");
86                 var commentElement = $("<div><span>Comment</span></div>").addClass("show-reply-form").click(function() {
87                         replyElement = $("#sone .post#" + postId + " .create-reply");
88                         replyElement.removeClass("hidden");
89                         replyElement.removeClass("light");
90                         (function(replyElement) {
91                                 replyElement.find("input.reply-input").blur(function() {
92                                         if ($(this).hasClass("default")) {
93                                                 replyElement.addClass("light");
94                                         }
95                                 }).focus(function() {
96                                         replyElement.removeClass("light");
97                                 });
98                         })(replyElement);
99                         textArea = replyElement.find("input.reply-input").focus().data("textarea");
100                         textArea.val(textArea.val() + "@sone://" + author + " ");
101                 });
102                 return commentElement;
103         })(postId, author);
104         $(insertAfterThisElement).after(commentElement.clone(true));
105         $(insertAfterThisElement).after(separator);
106 }
107
108 var translations = {};
109
110 /**
111  * Retrieves the translation for the given key and calls the callback function.
112  * The callback function takes a single parameter, the translated string.
113  *
114  * @param key
115  *            The key of the translation string
116  * @param callback
117  *            The callback function
118  */
119 function getTranslation(key, callback) {
120         if (key in translations) {
121                 callback(translations[key]);
122                 return;
123         }
124         ajaxGet("getTranslation.ajax", {"key": key}, function(data, textStatus) {
125                 if ((data != null) && data.success) {
126                         translations[key] = data.value;
127                         callback(data.value);
128                 }
129         });
130 }
131
132 /**
133  * Filters the given Sone ID, replacing all “~” characters by an underscore.
134  *
135  * @param soneId
136  *            The Sone ID to filter
137  * @returns The filtered Sone ID
138  */
139 function filterSoneId(soneId) {
140         return soneId.replace(/[^a-zA-Z0-9-]/g, "_");
141 }
142
143 /**
144  * Updates the status of the given Sone.
145  *
146  * @param soneId
147  *            The ID of the Sone to update
148  * @param status
149  *            The status of the Sone (“idle”, “unknown”, “inserting”,
150  *            “downloading”)
151  * @param modified
152  *            Whether the Sone is modified
153  * @param locked
154  *            Whether the Sone is locked
155  * @param lastUpdated
156  *            The date and time of the last update (formatted for display)
157  */
158 function updateSoneStatus(soneId, name, status, modified, locked, lastUpdated, lastUpdatedText) {
159         $("#sone .sone." + filterSoneId(soneId)).
160                 toggleClass("unknown", status == "unknown").
161                 toggleClass("idle", status == "idle").
162                 toggleClass("inserting", status == "inserting").
163                 toggleClass("downloading", status == "downloading").
164                 toggleClass("modified", modified);
165         $("#sone .sone." + filterSoneId(soneId) + " .lock").toggleClass("hidden", locked);
166         $("#sone .sone." + filterSoneId(soneId) + " .unlock").toggleClass("hidden", !locked);
167         if (lastUpdated != null) {
168                 $("#sone .sone." + filterSoneId(soneId) + " .last-update span.time").attr("title", lastUpdated).text(lastUpdatedText);
169         } else {
170                 getTranslation("View.Sone.Text.UnknownDate", function(unknown) {
171                         $("#sone .sone." + filterSoneId(soneId) + " .last-update span.time").text(unknown);
172                 });
173         }
174         $("#sone .sone." + filterSoneId(soneId) + " .profile-link a").text(name);
175 }
176
177 /**
178  * Enhances a “delete” button so that the confirmation is done on the same page.
179  *
180  * @param button
181  *            The button element
182  * @param text
183  *            The text to show on the button
184  * @param deleteCallback
185  *            The callback that actually deletes something
186  */
187 function enhanceDeleteButton(button, text, deleteCallback) {
188         (function(button) {
189                 newButton = $("<button></button>").addClass("confirm").hide().text(text).click(function() {
190                         $(this).fadeOut("slow");
191                         deleteCallback();
192                         return false;
193                 }).insertAfter(button);
194                 (function(button, newButton) {
195                         button.click(function() {
196                                 button.fadeOut("slow", function() {
197                                         newButton.fadeIn("slow");
198                                         $(document).one("click", function() {
199                                                 if (this != newButton.get(0)) {
200                                                         newButton.fadeOut(function() {
201                                                                 button.fadeIn();
202                                                         });
203                                                 }
204                                         });
205                                 });
206                                 return false;
207                         });
208                 })(button, newButton);
209         })($(button));
210 }
211
212 /**
213  * Enhances a post’s “delete” button.
214  *
215  * @param button
216  *            The button element
217  * @param postId
218  *            The ID of the post to delete
219  * @param text
220  *            The text to replace the button with
221  */
222 function enhanceDeletePostButton(button, postId, text) {
223         enhanceDeleteButton(button, text, function() {
224                 ajaxGet("deletePost.ajax", { "post": postId, "formPassword": getFormPassword() }, function(data, textStatus) {
225                         if (data == null) {
226                                 return;
227                         }
228                         if (data.success) {
229                                 $("#sone .post#" + postId).slideUp();
230                         } else if (data.error == "invalid-post-id") {
231                                 /* pretend the post is already gone. */
232                                 getPost(postId).slideUp();
233                         } else if (data.error == "auth-required") {
234                                 alert("You need to be logged in.");
235                         } else if (data.error == "not-authorized") {
236                                 alert("You are not allowed to delete this post.");
237                         }
238                 }, function(xmlHttpRequest, textStatus, error) {
239                         /* ignore error. */
240                 });
241         });
242 }
243
244 /**
245  * Enhances a reply’s “delete” button.
246  *
247  * @param button
248  *            The button element
249  * @param replyId
250  *            The ID of the reply to delete
251  * @param text
252  *            The text to replace the button with
253  */
254 function enhanceDeleteReplyButton(button, replyId, text) {
255         enhanceDeleteButton(button, text, function() {
256                 ajaxGet("deleteReply.ajax", { "reply": replyId, "formPassword": $("#sone #formPassword").text() }, function(data, textStatus) {
257                         if (data == null) {
258                                 return;
259                         }
260                         if (data.success) {
261                                 $("#sone .reply#" + replyId).slideUp();
262                         } else if (data.error == "invalid-reply-id") {
263                                 /* pretend the reply is already gone. */
264                                 getReply(replyId).slideUp();
265                         } else if (data.error == "auth-required") {
266                                 alert("You need to be logged in.");
267                         } else if (data.error == "not-authorized") {
268                                 alert("You are not allowed to delete this reply.");
269                         }
270                 }, function(xmlHttpRequest, textStatus, error) {
271                         /* ignore error. */
272                 });
273         });
274 }
275
276 function getFormPassword() {
277         return $("#sone #formPassword").text();
278 }
279
280 /**
281  * Returns the element of the Sone with the given ID.
282  *
283  * @param soneId
284  *            The ID of the Sone
285  * @returns All Sone elements with the given ID
286  */
287 function getSone(soneId) {
288         return $("#sone .sone").filter(function(index) {
289                 return $(".id", this).text() == soneId;
290         });
291 }
292
293 function getSoneElement(element) {
294         return $(element).closest(".sone");
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#" + postId);
336 }
337
338 function getPostElement(element) {
339         return $(element).closest(".post");
340 }
341
342 function getPostId(element) {
343         return getPostElement(element).attr("id");
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#" + replyId);
370 }
371
372 function getReplyElement(element) {
373         return $(element).closest(".reply");
374 }
375
376 function getReplyId(element) {
377         return getReplyElement(element).attr("id");
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#" + postId + " > .inner-part > .status-line .like").addClass("hidden");
445                 $("#sone .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#" + postId + " > .inner-part > .status-line .unlike").addClass("hidden");
458                 $("#sone .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#" + postId + " > .inner-part > .status-line .likes").toggleClass("hidden", data.likes == 0);
469                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes span.like-count").text(data.likes);
470                         $("#sone .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#" + replyId + " .status-line .like").addClass("hidden");
483                 $("#sone .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#" + replyId + " .status-line .unlike").addClass("hidden");
496                 $("#sone .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#" + replyId + " .status-line .likes").toggleClass("hidden", data.likes == 0);
607                         $("#sone .reply#" + replyId + " .status-line .likes span.like-count").text(data.likes);
608                         $("#sone .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#" + postId + " .create-reply").addClass("hidden");
717                                         $("#sone .post#" + postId + " .create-reply .sender").hide();
718                                         $("#sone .post#" + postId + " .create-reply .select-sender").show();
719                                         $("#sone .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-text.text", getPostElement(this)).toggleClass("hidden");
775                         $(".post-text.raw-text", getPostElement(this)).toggleClass("hidden");
776                         return false;
777                 });
778         });
779
780         /* add “comment” link. */
781         addCommentLink(getPostId(postElement), getPostAuthor(postElement), postElement, $(postElement).find(".post-status-line .permalink-author"));
782
783         /* process all replies. */
784         replyIds = [];
785         $(postElement).find(".reply").each(function() {
786                 replyIds.push(getReplyId(this));
787                 ajaxifyReply(this);
788         });
789         updateReplyTimes(replyIds.join(","));
790
791         /* process reply input fields. */
792         getTranslation("WebInterface.DefaultText.Reply", function(text) {
793                 $(postElement).find("input.reply-input").each(function() {
794                         registerInputTextareaSwap(this, text, "text", false, false);
795                 });
796         });
797
798         /* process sender selection. */
799         $(".select-sender", postElement).css("display", "inline");
800         $(".sender", postElement).hide();
801         $(".select-sender button", postElement).click(function() {
802                 $(".sender", postElement).show();
803                 $(".select-sender", postElement).hide();
804                 return false;
805         });
806
807         /* mark everything as known on click. */
808         $(postElement).click(function(event) {
809                 if ($(event.target).hasClass("click-to-show")) {
810                         return false;
811                 }
812                 markPostAsKnown(this);
813         });
814
815         /* hide reply input field. */
816         $(postElement).find(".create-reply").addClass("hidden");
817 }
818
819 /**
820  * Ajaxifies the given reply element.
821  *
822  * @param replyElement
823  *            The reply element to ajaxify
824  */
825 function ajaxifyReply(replyElement) {
826         $(replyElement).find(".like-reply").submit(function() {
827                 likeReply(getReplyId(this));
828                 return false;
829         });
830         $(replyElement).find(".unlike-reply").submit(function() {
831                 unlikeReply(getReplyId(this));
832                 return false;
833         });
834         (function(replyElement) {
835                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
836                         $(replyElement).find(".delete-reply button").each(function() {
837                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
838                         });
839                 });
840         })(replyElement);
841         addCommentLink(getPostId(replyElement), getReplyAuthor(replyElement), replyElement, $(replyElement).find(".reply-status-line .permalink-author"));
842
843         /* convert “show source” link into javascript function. */
844         $(replyElement).find(".show-reply-source").each(function() {
845                 $("a", this).click(function() {
846                         $(".reply-text.text", getReplyElement(this)).toggleClass("hidden");
847                         $(".reply-text.raw-text", getReplyElement(this)).toggleClass("hidden");
848                         return false;
849                 });
850         });
851
852         /* convert trust control buttons to javascript functions. */
853         $(replyElement).find(".reply-trust").submit(function() {
854                 trustSone(getReplyAuthor(this));
855                 return false;
856         });
857         $(replyElement).find(".reply-distrust").submit(function() {
858                 distrustSone(getReplyAuthor(this));
859                 return false;
860         });
861         $(replyElement).find(".reply-untrust").submit(function() {
862                 untrustSone(getReplyAuthor(this));
863                 return false;
864         });
865 }
866
867 /**
868  * Ajaxifies the given notification by replacing the form with AJAX.
869  *
870  * @param notification
871  *            jQuery object representing the notification.
872  */
873 function ajaxifyNotification(notification) {
874         notification.find("form").submit(function() {
875                 return false;
876         });
877         notification.find("input[name=returnPage]").val($.url.attr("relative"));
878         if (notification.find(".short-text").length > 0) {
879                 notification.find(".short-text").removeClass("hidden");
880                 notification.find(".text").addClass("hidden");
881         }
882         notification.find("form.mark-as-read button").click(function() {
883                 ajaxPost("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": $(":input[name=type]", this.form).val(), "id": $(":input[name=id]", this.form).val()});
884         });
885         notification.find("a[class^='link-']").each(function() {
886                 linkElement = $(this);
887                 if (linkElement.is("[href^='viewPost']")) {
888                         id = linkElement.attr("class").substr(5);
889                         if (hasPost(id)) {
890                                 linkElement.attr("href", "#post-" + id).addClass("in-page-link");
891                         }
892                 }
893         });
894         notification.find("form.dismiss button").click(function() {
895                 ajaxGet("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.attr("id") }, function(data, textStatus) {
896                         /* dismiss in case of error, too. */
897                         notification.slideUp();
898                 }, function(xmlHttpRequest, textStatus, error) {
899                         /* ignore error. */
900                 });
901         });
902         return notification;
903 }
904
905 /**
906  * Retrieves element IDs from notification elements.
907  *
908  * @param notification
909  *            The notification element
910  * @param selector
911  *            The selector of the element containing the ID as text
912  * @returns All extracted IDs
913  */
914 function getElementIds(notification, selector) {
915         elementIds = [];
916         $(selector, notification).each(function() {
917                 elementIds.push($(this).text());
918         });
919         return elementIds;
920 }
921
922 /**
923  * Compares the given notification elements and calls {@link #markSoneAsKnown()}
924  * for every ID that is contained in the old notification but not in the new.
925  *
926  * @param oldNotification
927  *            The old notification element
928  * @param newNotification
929  *            The new notification element
930  */
931 function checkForRemovedSones(oldNotification, newNotification) {
932         if (getNotificationId(oldNotification) != "new-sone-notification") {
933                 return;
934         }
935         oldIds = getElementIds(oldNotification, ".new-sone-id");
936         newIds = getElementIds(newNotification, ".new-sone-id");
937         $.each(oldIds, function(index, value) {
938                 if ($.inArray(value, newIds) == -1) {
939                         markSoneAsKnown(getSone(value), true);
940                 }
941         });
942 }
943
944 /**
945  * Compares the given notification elements and calls {@link #markPostAsKnown()}
946  * for every ID that is contained in the old notification but not in the new.
947  *
948  * @param oldNotification
949  *            The old notification element
950  * @param newNotification
951  *            The new notification element
952  */
953 function checkForRemovedPosts(oldNotification, newNotification) {
954         if (getNotificationId(oldNotification) != "new-post-notification") {
955                 return;
956         }
957         oldIds = getElementIds(oldNotification, ".post-id");
958         newIds = getElementIds(newNotification, ".post-id");
959         $.each(oldIds, function(index, value) {
960                 if ($.inArray(value, newIds) == -1) {
961                         markPostAsKnown(getPost(value), true);
962                 }
963         });
964 }
965
966 /**
967  * Compares the given notification elements and calls
968  * {@link #markReplyAsKnown()} for every ID that is contained in the old
969  * notification but not in the new.
970  *
971  * @param oldNotification
972  *            The old notification element
973  * @param newNotification
974  *            The new notification element
975  */
976 function checkForRemovedReplies(oldNotification, newNotification) {
977         if (getNotificationId(oldNotification) != "new-replies-notification") {
978                 return;
979         }
980         oldIds = getElementIds(oldNotification, ".reply-id");
981         newIds = getElementIds(newNotification, ".reply-id");
982         $.each(oldIds, function(index, value) {
983                 if ($.inArray(value, newIds) == -1) {
984                         markReplyAsKnown(getReply(value), true);
985                 }
986         });
987 }
988
989 function getStatus() {
990         ajaxGet("getStatus.ajax", isViewSonePage() ? {"soneIds": getShownSoneId() } : {"loadAllSones": isKnownSonesPage()}, function(data, textStatus) {
991                 if ((data != null) && data.success) {
992                         /* process Sone information. */
993                         $.each(data.sones, function(index, value) {
994                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdatedUnknown ? null : value.lastUpdated, value.lastUpdatedText);
995                         });
996                         /* search for removed notifications. */
997                         $("#sone #notification-area .notification").each(function() {
998                                 notificationId = $(this).attr("id");
999                                 foundNotification = false;
1000                                 $.each(data.notifications, function(index, value) {
1001                                         if (value.id == notificationId) {
1002                                                 foundNotification = true;
1003                                                 return false;
1004                                         }
1005                                 });
1006                                 if (!foundNotification) {
1007                                         if (notificationId == "new-sone-notification") {
1008                                                 $(".new-sone-id", this).each(function(index, element) {
1009                                                         soneId = $(this).text();
1010                                                         markSoneAsKnown(getSone(soneId), true);
1011                                                 });
1012                                         } else if (notificationId == "new-post-notification") {
1013                                                 $(".post-id", this).each(function(index, element) {
1014                                                         postId = $(this).text();
1015                                                         markPostAsKnown(getPost(postId), true);
1016                                                 });
1017                                         } else if (notificationId == "new-replies-notification") {
1018                                                 $(".reply-id", this).each(function(index, element) {
1019                                                         replyId = $(this).text();
1020                                                         markReplyAsKnown(getReply(replyId), true);
1021                                                 });
1022                                         }
1023                                         $(this).slideUp("normal", function() {
1024                                                 $(this).remove();
1025                                                 /* remove activity when no notifications are visible. */
1026                                                 if ($("#sone #notification-area .notification").length == 0) {
1027                                                         resetActivity();
1028                                                 }
1029                                         });
1030                                 }
1031                         });
1032                         /* process notifications. */
1033                         notificationIds = [];
1034                         $.each(data.notifications, function(index, value) {
1035                                 oldNotification = getNotification(value.id);
1036                                 if ((oldNotification.length == 0) || (value.lastUpdatedTime > getNotificationLastUpdatedTime(oldNotification))) {
1037                                         notificationIds.push(value.id);
1038                                 }
1039                         });
1040                         if (notificationIds.length > 0) {
1041                                 loadNotifications(notificationIds);
1042                         }
1043                         /* process new posts. */
1044                         $.each(data.newPosts, function(index, value) {
1045                                 loadNewPost(value.id, value.sone, value.recipient, value.time);
1046                         });
1047                         /* process new replies. */
1048                         $.each(data.newReplies, function(index, value) {
1049                                 loadNewReply(value.id, value.sone, value.post, value.postSone);
1050                         });
1051                         /* do it again in 5 seconds. */
1052                         setTimeout(getStatus, 5000);
1053                 } else {
1054                         /* data.success was false, wait 30 seconds. */
1055                         setTimeout(getStatus, 30000);
1056                 }
1057         }, function() {
1058                 statusRequestQueued = false;
1059                 ajaxError();
1060         });
1061 }
1062
1063 /**
1064  * Requests multiple notifications from Sone and displays them.
1065  *
1066  * @param notificationIds
1067  *            Array of IDs of the notifications to load
1068  */
1069 function loadNotifications(notificationIds) {
1070         ajaxGet("getNotification.ajax", {"notifications": notificationIds.join(",")}, function(data, textStatus) {
1071                 if (!data || !data.success) {
1072                         // TODO - show error
1073                         return;
1074                 }
1075                 $.each(data.notifications, function(index, value) {
1076                         oldNotification = getNotification(value.id);
1077                         notification = ajaxifyNotification(createNotification(value.id, value.lastUpdatedTime, value.text, value.dismissable)).hide();
1078                         if (oldNotification.length != 0) {
1079                                 if ((oldNotification.find(".short-text").length > 0) && (notification.find(".short-text").length > 0)) {
1080                                         opened = oldNotification.is(":visible") && oldNotification.find(".short-text").hasClass("hidden");
1081                                         notification.find(".short-text").toggleClass("hidden", opened);
1082                                         notification.find(".text").toggleClass("hidden", !opened);
1083                                 }
1084                                 checkForRemovedSones(oldNotification, notification);
1085                                 checkForRemovedPosts(oldNotification, notification);
1086                                 checkForRemovedReplies(oldNotification, notification);
1087                                 oldNotification.replaceWith(notification.show());
1088                         } else {
1089                                 $("#sone #notification-area").append(notification);
1090                                 notification.slideDown();
1091                                 setActivity();
1092                         }
1093                 });
1094         });
1095 }
1096
1097 /**
1098  * Returns the ID of the currently logged in Sone.
1099  *
1100  * @return The ID of the current Sone, or an empty string if no Sone is logged
1101  *         in
1102  */
1103 function getCurrentSoneId() {
1104         return $("#currentSoneId").text();
1105 }
1106
1107 /**
1108  * Returns the content of the page-id attribute.
1109  *
1110  * @returns The page ID
1111  */
1112 function getPageId() {
1113         return $("#sone .page-id").text();
1114 }
1115
1116 /**
1117  * Returns whether the current page is the index page.
1118  *
1119  * @returns {Boolean} <code>true</code> if the current page is the index page,
1120  *          <code>false</code> otherwise
1121  */
1122 function isIndexPage() {
1123         return getPageId() == "index";
1124 }
1125
1126 /**
1127  * Returns the current page of the selected pagination. If no pagination can be
1128  * found with the given selector, {@code 1} is returned.
1129  *
1130  * @param paginationSelector
1131  *            The pagination selector
1132  * @returns The current page of the pagination
1133  */
1134 function getPage(paginationSelector) {
1135         pagination = $(paginationSelector);
1136         if (pagination.length > 0) {
1137                 return $(".current-page", paginationSelector).text();
1138         }
1139         return 1;
1140 }
1141
1142 /**
1143  * Returns whether the current page is a “view Sone” page.
1144  *
1145  * @returns {Boolean} <code>true</code> if the current page is a “view Sone”
1146  *          page, <code>false</code> otherwise
1147  */
1148 function isViewSonePage() {
1149         return getPageId() == "view-sone";
1150 }
1151
1152 /**
1153  * Returns the ID of the currently shown Sone. This will only return a sensible
1154  * value if isViewSonePage() returns <code>true</code>.
1155  *
1156  * @returns The ID of the currently shown Sone
1157  */
1158 function getShownSoneId() {
1159         return $("#sone .sone-id").text();
1160 }
1161
1162 /**
1163  * Returns whether the current page is a “view post” page.
1164  *
1165  * @returns {Boolean} <code>true</code> if the current page is a “view post”
1166  *          page, <code>false</code> otherwise
1167  */
1168 function isViewPostPage() {
1169         return getPageId() == "view-post";
1170 }
1171
1172 /**
1173  * Returns the ID of the currently shown post. This will only return a sensible
1174  * value if isViewPostPage() returns <code>true</code>.
1175  *
1176  * @returns The ID of the currently shown post
1177  */
1178 function getShownPostId() {
1179         return $("#sone .post-id").text();
1180 }
1181
1182 /**
1183  * Returns whether the current page is the “known Sones” page.
1184  *
1185  * @returns {Boolean} <code>true</code> if the current page is the “known
1186  *          Sones” page, <code>false</code> otherwise
1187  */
1188 function isKnownSonesPage() {
1189         return getPageId() == "known-sones";
1190 }
1191
1192 /**
1193  * Returns whether a post with the given ID exists on the current page.
1194  *
1195  * @param postId
1196  *            The post ID to check for
1197  * @returns {Boolean} <code>true</code> if a post with the given ID already
1198  *          exists on the page, <code>false</code> otherwise
1199  */
1200 function hasPost(postId) {
1201         return $(".post#" + postId).length > 0;
1202 }
1203
1204 /**
1205  * Returns whether a reply with the given ID exists on the current page.
1206  *
1207  * @param replyId
1208  *            The reply ID to check for
1209  * @returns {Boolean} <code>true</code> if a reply with the given ID already
1210  *          exists on the page, <code>false</code> otherwise
1211  */
1212 function hasReply(replyId) {
1213         return $("#sone .reply#" + replyId).length > 0;
1214 }
1215
1216 function loadNewPost(postId, soneId, recipientId, time) {
1217         if (hasPost(postId)) {
1218                 return;
1219         }
1220         if (!isIndexPage() || (getPage(".pagination-index") > 1)) {
1221                 if (!isViewPostPage() || (getShownPostId() != postId)) {
1222                         if (!isViewSonePage() || ((getShownSoneId() != soneId) && (getShownSoneId() != recipientId))) {
1223                                 return;
1224                         }
1225                 }
1226         }
1227         if (getPostTime($("#sone .post").last()) > time) {
1228                 return;
1229         }
1230         ajaxGet("getPost.ajax", { "post" : postId }, function(data, textStatus) {
1231                 if ((data != null) && data.success) {
1232                         if (hasPost(data.post.id)) {
1233                                 return;
1234                         }
1235                         if ((!isIndexPage() || (getPage(".pagination-index") > 1)) && !(isViewSonePage() && ((getShownSoneId() == data.post.sone) || (getShownSoneId() == data.post.recipient)))) {
1236                                 return;
1237                         }
1238                         var firstOlderPost = null;
1239                         $("#sone .post").each(function() {
1240                                 if (getPostTime(this) < data.post.time) {
1241                                         firstOlderPost = $(this);
1242                                         return false;
1243                                 }
1244                         });
1245                         newPost = $(data.post.html).addClass("hidden");
1246                         if (firstOlderPost != null) {
1247                                 newPost.insertBefore(firstOlderPost);
1248                         }
1249                         ajaxifyPost(newPost);
1250                         updatePostTimes(data.post.id);
1251                         newPost.slideDown();
1252                         setActivity();
1253                 }
1254         });
1255 }
1256
1257 function loadNewReply(replyId, soneId, postId, postSoneId) {
1258         if (hasReply(replyId)) {
1259                 return;
1260         }
1261         if (!hasPost(postId)) {
1262                 return;
1263         }
1264         ajaxGet("getReply.ajax", { "reply": replyId }, function(data, textStatus) {
1265                 /* find post. */
1266                 if ((data != null) && data.success) {
1267                         if (hasReply(data.reply.id)) {
1268                                 return;
1269                         }
1270                         $("#sone .post#" + data.reply.postId).each(function() {
1271                                 var firstNewerReply = null;
1272                                 $(this).find(".replies .reply").each(function() {
1273                                         if (getReplyTime(this) > data.reply.time) {
1274                                                 firstNewerReply = $(this);
1275                                                 return false;
1276                                         }
1277                                 });
1278                                 newReply = $(data.reply.html).addClass("hidden");
1279                                 if (firstNewerReply != null) {
1280                                         newReply.insertBefore(firstNewerReply);
1281                                 } else {
1282                                         if ($(this).find(".replies .create-reply")) {
1283                                                 $(this).find(".replies .create-reply").before(newReply);
1284                                         } else {
1285                                                 $(this).find(".replies").append(newReply);
1286                                         }
1287                                 }
1288                                 ajaxifyReply(newReply);
1289                                 updateReplyTimes(data.reply.id);
1290                                 newReply.slideDown();
1291                                 setActivity();
1292                                 return false;
1293                         });
1294                 }
1295         });
1296 }
1297
1298 /**
1299  * Marks the given Sone as known if it is still new.
1300  *
1301  * @param soneElement
1302  *            The Sone to mark as known
1303  * @param skipRequest
1304  *            true to skip the JSON request, false or omit to perform the JSON
1305  *            request
1306  */
1307 function markSoneAsKnown(soneElement, skipRequest) {
1308         if ($(soneElement).is(".new")) {
1309                 $(soneElement).removeClass("new");
1310                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1311                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "sone", "id": getSoneId(soneElement)});
1312                 }
1313         }
1314 }
1315
1316 function markPostAsKnown(postElements, skipRequest) {
1317         $(postElements).each(function() {
1318                 postElement = this;
1319                 if ($(postElement).hasClass("new")) {
1320                         (function(postElement) {
1321                                 $(postElement).removeClass("new");
1322                                 $(".click-to-show", postElement).removeClass("new");
1323                                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1324                                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "post", "id": getPostId(postElement)});
1325                                 }
1326                         })(postElement);
1327                 }
1328         });
1329         markReplyAsKnown($(postElements).find(".reply"));
1330 }
1331
1332 function markReplyAsKnown(replyElements, skipRequest) {
1333         $(replyElements).each(function() {
1334                 replyElement = this;
1335                 if ($(replyElement).hasClass("new")) {
1336                         (function(replyElement) {
1337                                 $(replyElement).removeClass("new");
1338                                 if ((typeof skipRequest == "undefined") || !skipRequest) {
1339                                         ajaxGet("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "reply", "id": getReplyId(replyElement)});
1340                                 }
1341                         })(replyElement);
1342                 }
1343         });
1344 }
1345
1346 /**
1347  * Updates the time of the post with the given ID.
1348  *
1349  * @param postId
1350  *            The ID of the post to update
1351  * @param timeText
1352  *            The text of the time to show
1353  * @param refreshTime
1354  *            The refresh time after which to request a new time (in seconds)
1355  * @param tooltip
1356  *            The tooltip to show
1357  */
1358 function updatePostTime(postId, timeText, refreshTime, tooltip) {
1359         if (!getPost(postId).is(":visible")) {
1360                 return;
1361         }
1362         getPost(postId).find(".post-status-line > .time a").html(timeText).attr("title", tooltip);
1363         (function(postId, refreshTime) {
1364                 setTimeout(function() {
1365                         updatePostTimes(postId);
1366                 }, refreshTime * 1000);
1367         })(postId, refreshTime);
1368 }
1369
1370 /**
1371  * Requests new rendered times for the posts with the given IDs.
1372  *
1373  * @param postIds
1374  *            Comma-separated post IDs
1375  */
1376 function updatePostTimes(postIds) {
1377         ajaxGet("getTimes.ajax", { "posts" : postIds }, function(data, textStatus) {
1378                 if ((data != null) && data.success) {
1379                         $.each(data.postTimes, function(index, value) {
1380                                 updatePostTime(index, value.timeText, value.refreshTime, value.tooltip);
1381                         });
1382                 }
1383         });
1384 }
1385
1386 /**
1387  * Updates the time of the reply with the given ID.
1388  *
1389  * @param postId
1390  *            The ID of the reply to update
1391  * @param timeText
1392  *            The text of the time to show
1393  * @param refreshTime
1394  *            The refresh time after which to request a new time (in seconds)
1395  * @param tooltip
1396  *            The tooltip to show
1397  */
1398 function updateReplyTime(replyId, timeText, refreshTime, tooltip) {
1399         getReply(replyId).find(".reply-status-line > .time").html(timeText).attr("title", tooltip);
1400         (function(replyId, refreshTime) {
1401                 setTimeout(function() {
1402                         updateReplyTimes(replyId);
1403                 }, refreshTime * 1000);
1404         })(replyId, refreshTime);
1405 }
1406
1407 /**
1408  * Requests new rendered times for the posts with the given IDs.
1409  *
1410  * @param postIds
1411  *            Comma-separated post IDs
1412  */
1413 function updateReplyTimes(replyIds) {
1414         ajaxGet("getTimes.ajax", { "replies" : replyIds }, function(data, textStatus) {
1415                 if ((data != null) && data.success) {
1416                         $.each(data.replyTimes, function(index, value) {
1417                                 updateReplyTime(index, value.timeText, value.refreshTime, value.tooltip);
1418                         });
1419                 }
1420         });
1421 }
1422
1423 function resetActivity() {
1424         title = document.title;
1425         if (title.indexOf('(') == 0) {
1426                 setTitle(title.substr(title.indexOf(' ') + 1));
1427         }
1428         iconBlinking = false;
1429 }
1430
1431 function setActivity() {
1432         if (!focus) {
1433                 title = document.title;
1434                 if (title.indexOf('(') != 0) {
1435                         setTitle("(!) " + title);
1436                 }
1437                 if (!iconBlinking) {
1438                         setTimeout(toggleIcon, 1500);
1439                         iconBlinking = true;
1440                 }
1441         }
1442 }
1443
1444 /**
1445  * Sets the window title after a small delay to prevent race-condition issues.
1446  *
1447  * @param title
1448  *            The title to set
1449  */
1450 function setTitle(title) {
1451         setTimeout(function() {
1452                 document.title = title;
1453         }, 50);
1454 }
1455
1456 /** Whether the icon is currently showing activity. */
1457 var iconActive = false;
1458
1459 /** Whether the icon is currently supposed to blink. */
1460 var iconBlinking = false;
1461
1462 /**
1463  * Toggles the icon. If the window has gained focus and the icon is still
1464  * showing the activity state, it is returned to normal.
1465  */
1466 function toggleIcon() {
1467         if (focus || !iconBlinking) {
1468                 if (iconActive) {
1469                         changeIcon("images/icon.png");
1470                         iconActive = false;
1471                 }
1472                 iconBlinking = false;
1473         } else {
1474                 iconActive = !iconActive;
1475                 changeIcon(iconActive ? "images/icon-activity.png" : "images/icon.png");
1476                 setTimeout(toggleIcon, 1500);
1477         }
1478 }
1479
1480 /**
1481  * Changes the icon of the page.
1482  *
1483  * @param iconUrl
1484  *            The new URL of the icon
1485  */
1486 function changeIcon(iconUrl) {
1487         $("link[rel=icon]").remove();
1488         $("head").append($("<link>").attr("rel", "icon").attr("type", "image/png").attr("href", iconUrl));
1489         $("iframe[id=icon-update]")[0].src += "";
1490 }
1491
1492 /**
1493  * Creates a new notification.
1494  *
1495  * @param id
1496  *            The ID of the notificaiton
1497  * @param text
1498  *            The text of the notification
1499  * @param dismissable
1500  *            <code>true</code> if the notification can be dismissed by the
1501  *            user
1502  */
1503 function createNotification(id, lastUpdatedTime, text, dismissable) {
1504         notification = $("<div></div>").addClass("notification").attr("id", id).attr("lastUpdatedTime", lastUpdatedTime);
1505         if (dismissable) {
1506                 dismissForm = $("#sone #notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id");
1507                 dismissForm.find("input[name=notification]").val(id);
1508                 notification.append(dismissForm);
1509         }
1510         notification.append(text);
1511         return notification;
1512 }
1513
1514 /**
1515  * Shows the details of the notification with the given ID.
1516  *
1517  * @param notificationId
1518  *            The ID of the notification
1519  */
1520 function showNotificationDetails(notificationId) {
1521         $("#sone .notification#" + notificationId + " .text").removeClass("hidden");
1522         $("#sone .notification#" + notificationId + " .short-text").addClass("hidden");
1523 }
1524
1525 /**
1526  * Deletes the field with the given ID from the profile.
1527  *
1528  * @param fieldId
1529  *            The ID of the field to delete
1530  */
1531 function deleteProfileField(fieldId) {
1532         ajaxGet("deleteProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId}, function(data, textStatus) {
1533                 if (data && data.success) {
1534                         $("#sone .profile-field#" + data.field.id).slideUp();
1535                 }
1536         });
1537 }
1538
1539 /**
1540  * Renames a profile field.
1541  *
1542  * @param fieldId
1543  *            The ID of the field to rename
1544  * @param newName
1545  *            The new name of the field
1546  * @param successFunction
1547  *            Called when the renaming was successful
1548  */
1549 function editProfileField(fieldId, newName, successFunction) {
1550         ajaxGet("editProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "name": newName}, function(data, textStatus) {
1551                 if (data && data.success) {
1552                         successFunction();
1553                 }
1554         });
1555 }
1556
1557 /**
1558  * Moves the profile field with the given ID one slot in the given direction.
1559  *
1560  * @param fieldId
1561  *            The ID of the field to move
1562  * @param direction
1563  *            The direction to move in (“up” or “down”)
1564  * @param successFunction
1565  *            Function to call on success
1566  */
1567 function moveProfileField(fieldId, direction, successFunction) {
1568         ajaxGet("moveProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "direction": direction}, function(data, textStatus) {
1569                 if (data && data.success) {
1570                         successFunction();
1571                 }
1572         });
1573 }
1574
1575 /**
1576  * Moves the profile field with the given ID up one slot.
1577  *
1578  * @param fieldId
1579  *            The ID of the field to move
1580  * @param successFunction
1581  *            Function to call on success
1582  */
1583 function moveProfileFieldUp(fieldId, successFunction) {
1584         moveProfileField(fieldId, "up", successFunction);
1585 }
1586
1587 /**
1588  * Moves the profile field with the given ID down one slot.
1589  *
1590  * @param fieldId
1591  *            The ID of the field to move
1592  * @param successFunction
1593  *            Function to call on success
1594  */
1595 function moveProfileFieldDown(fieldId, successFunction) {
1596         moveProfileField(fieldId, "down", successFunction);
1597 }
1598
1599 var statusRequestQueued = true;
1600
1601 /**
1602  * Sets the status of the web interface as offline.
1603  */
1604 function ajaxError() {
1605         online = false;
1606         toggleOfflineMarker(true);
1607         if (!statusRequestQueued) {
1608                 setTimeout(getStatus, 5000);
1609                 statusRequestQueued = true;
1610         }
1611 }
1612
1613 /**
1614  * Sets the status of the web interface as online.
1615  */
1616 function ajaxSuccess() {
1617         online = true;
1618         toggleOfflineMarker(false);
1619 }
1620
1621 /**
1622  * Shows or hides the offline marker.
1623  *
1624  * @param visible
1625  *            {@code true} to display the offline marker, {@code false} to hide
1626  *            it
1627  */
1628 function toggleOfflineMarker(visible) {
1629         /* jQuery documentation says toggle() works the other way around?! */
1630         $("#sone #offline-marker").toggle(visible);
1631         if (visible) {
1632                 $("#sone #main").addClass("offline");
1633         } else {
1634                 $("#sone #main").removeClass("offline");
1635         }
1636 }
1637
1638 //
1639 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
1640 //
1641
1642 var focus = true;
1643 var online = true;
1644
1645 $(document).ready(function() {
1646
1647         /* this initializes the status update input field. */
1648         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
1649                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
1650                 $("#sone #update-status .select-sender").css("display", "inline");
1651                 $("#sone #update-status .sender").hide();
1652                 $("#sone #update-status .select-sender button").click(function() {
1653                         $("#sone #update-status .sender").show();
1654                         $("#sone #update-status .select-sender").hide();
1655                         return false;
1656                 });
1657                 $("#sone #update-status").submit(function() {
1658                         button = $("button:submit", this);
1659                         button.attr("disabled", "disabled");
1660                         if ($(this).find(":input.default:enabled").length > 0) {
1661                                 return false;
1662                         }
1663                         sender = $(this).find(":input[name=sender]").val();
1664                         text = $(this).find(":input[name=text]:enabled").val();
1665                         ajaxGet("createPost.ajax", { "formPassword": getFormPassword(), "sender": sender, "text": text }, function(data, textStatus) {
1666                                 button.removeAttr("disabled");
1667                         });
1668                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1669                         $(this).find(":input[name=text]:enabled").val("").blur();
1670                         $(this).find(".sender").hide();
1671                         $(this).find(".select-sender").show();
1672                         return false;
1673                 });
1674         });
1675
1676         /* ajaxify the search input field. */
1677         getTranslation("WebInterface.DefaultText.Search", function(defaultText) {
1678                 registerInputTextareaSwap("#sone #search input[name=query]", defaultText, "query", false, true);
1679         });
1680
1681         /* ajaxify input field on “view Sone” page. */
1682         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
1683                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
1684                 $("#sone #post-message .select-sender").css("display", "inline");
1685                 $("#sone #post-message .sender").hide();
1686                 $("#sone #post-message .select-sender button").click(function() {
1687                         $("#sone #post-message .sender").show();
1688                         $("#sone #post-message .select-sender").hide();
1689                         return false;
1690                 });
1691                 $("#sone #post-message").submit(function() {
1692                         sender = $(this).find(":input[name=sender]").val();
1693                         text = $(this).find(":input[name=text]:enabled").val();
1694                         ajaxGet("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "sender": sender, "text": text });
1695                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1696                         $(this).find(":input[name=text]:enabled").val("").blur();
1697                         $(this).find(".sender").hide();
1698                         $(this).find(".select-sender").show();
1699                         return false;
1700                 });
1701         });
1702
1703         /* Ajaxifies all posts. */
1704         /* calling getTranslation here will cache the necessary values. */
1705         getTranslation("WebInterface.Confirmation.DeletePostButton", function(text) {
1706                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(text) {
1707                         getTranslation("WebInterface.DefaultText.Reply", function(text) {
1708                                 $("#sone .post").each(function() {
1709                                         ajaxifyPost(this);
1710                                 });
1711                         });
1712                 });
1713         });
1714
1715         /* update post times. */
1716         postIds = [];
1717         $("#sone .post").each(function() {
1718                 postIds.push(getPostId(this));
1719         });
1720         updatePostTimes(postIds.join(","));
1721
1722         /* hides all replies but the latest two. */
1723         if (!isViewPostPage()) {
1724                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
1725                         $("#sone .post .replies").each(function() {
1726                                 allReplies = $(this).find(".reply");
1727                                 if (allReplies.length > 2) {
1728                                         newHidden = false;
1729                                         for (replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1730                                                 $(allReplies[replyIndex]).addClass("hidden");
1731                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1732                                         }
1733                                         clickToShowElement = $("<div></div>").addClass("click-to-show");
1734                                         if (newHidden) {
1735                                                 clickToShowElement.addClass("new");
1736                                         }
1737                                         (function(clickToShowElement, allReplies, text) {
1738                                                 clickToShowElement.text(text);
1739                                                 clickToShowElement.click(function() {
1740                                                         allReplies.removeClass("hidden");
1741                                                         clickToShowElement.addClass("hidden");
1742                                                 });
1743                                         })(clickToShowElement, allReplies, text);
1744                                         $(allReplies[0]).before(clickToShowElement);
1745                                 }
1746                         });
1747                 });
1748         }
1749
1750         $("#sone .sone").each(function() {
1751                 ajaxifySone($(this));
1752         });
1753
1754         /* process all existing notifications, ajaxify dismiss buttons. */
1755         $("#sone #notification-area .notification").each(function() {
1756                 ajaxifyNotification($(this));
1757         });
1758
1759         /* disable all permalinks. */
1760         $(".permalink").click(function() {
1761                 return false;
1762         });
1763
1764         /* activate status polling. */
1765         setTimeout(getStatus, 5000);
1766
1767         /* reset activity counter when the page has focus. */
1768         $(window).focus(function() {
1769                 focus = true;
1770                 resetActivity();
1771         }).blur(function() {
1772                 focus = false;
1773         });
1774
1775 });