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