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