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