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