Add method to retrieve a Sone element by its ID.
[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                                 alert("Invalid post ID given!");
222                         } else if (data.error == "auth-required") {
223                                 alert("You need to be logged in.");
224                         } else if (data.error == "not-authorized") {
225                                 alert("You are not allowed to delete this post.");
226                         }
227                 }, function(xmlHttpRequest, textStatus, error) {
228                         /* ignore error. */
229                 });
230         });
231 }
232
233 /**
234  * Enhances a reply’s “delete” button.
235  *
236  * @param button
237  *            The button element
238  * @param replyId
239  *            The ID of the reply to delete
240  * @param text
241  *            The text to replace the button with
242  */
243 function enhanceDeleteReplyButton(button, replyId, text) {
244         enhanceDeleteButton(button, text, function() {
245                 $.getJSON("deleteReply.ajax", { "reply": replyId, "formPassword": $("#sone #formPassword").text() }, function(data, textStatus) {
246                         if (data == null) {
247                                 return;
248                         }
249                         if (data.success) {
250                                 $("#sone .reply#" + replyId).slideUp();
251                         } else if (data.error == "invalid-reply-id") {
252                                 alert("Invalid reply ID given!");
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").text() == soneId;
278         });
279 }
280
281 function getSoneElement(element) {
282         return $(element).closest(".sone");
283 }
284
285 /**
286  * Generates a list of Sones by concatening the names of the given sones with a
287  * new line character (“\n”).
288  *
289  * @param sones
290  *            The sones to format
291  * @returns {String} The created string
292  */
293 function generateSoneList(sones) {
294         var soneList = "";
295         $.each(sones, function() {
296                 if (soneList != "") {
297                         soneList += ", ";
298                 }
299                 soneList += this.name;
300         });
301         return soneList;
302 }
303
304 /**
305  * Returns the ID of the Sone that this element belongs to.
306  *
307  * @param element
308  *            The element to locate the matching Sone ID for
309  * @returns The ID of the Sone, or undefined
310  */
311 function getSoneId(element) {
312         return getSoneElement(element).find(".id").text();
313 }
314
315 /**
316  * Returns the element of the post with the given ID.
317  *
318  * @param postId
319  *            The ID of the post
320  * @returns The element of the post
321  */
322 function getPost(postId) {
323         return $("#sone .post#" + postId);
324 }
325
326 function getPostElement(element) {
327         return $(element).closest(".post");
328 }
329
330 function getPostId(element) {
331         return getPostElement(element).attr("id");
332 }
333
334 function getPostTime(element) {
335         return getPostElement(element).find(".post-time").text();
336 }
337
338 /**
339  * Returns the author of the post the given element belongs to.
340  *
341  * @param element
342  *            The element whose post to get the author for
343  * @returns The ID of the authoring Sone
344  */
345 function getPostAuthor(element) {
346         return getPostElement(element).find(".post-author").text();
347 }
348
349 /**
350  * Returns the element of the reply with the given ID.
351  *
352  * @param replyId
353  *            The ID of the reply
354  * @returns The element of the reply
355  */
356 function getReply(replyId) {
357         return $("#sone .reply#" + replyId);
358 }
359
360 function getReplyElement(element) {
361         return $(element).closest(".reply");
362 }
363
364 function getReplyId(element) {
365         return getReplyElement(element).attr("id");
366 }
367
368 function getReplyTime(element) {
369         return getReplyElement(element).find(".reply-time").text();
370 }
371
372 /**
373  * Returns the author of the reply the given element belongs to.
374  *
375  * @param element
376  *            The element whose reply to get the author for
377  * @returns The ID of the authoring Sone
378  */
379 function getReplyAuthor(element) {
380         return getReplyElement(element).find(".reply-author").text();
381 }
382
383 function likePost(postId) {
384         $.getJSON("like.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
385                 if ((data == null) || !data.success) {
386                         return;
387                 }
388                 $("#sone .post#" + postId + " > .inner-part > .status-line .like").addClass("hidden");
389                 $("#sone .post#" + postId + " > .inner-part > .status-line .unlike").removeClass("hidden");
390                 updatePostLikes(postId);
391         }, function(xmlHttpRequest, textStatus, error) {
392                 /* ignore error. */
393         });
394 }
395
396 function unlikePost(postId) {
397         $.getJSON("unlike.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
398                 if ((data == null) || !data.success) {
399                         return;
400                 }
401                 $("#sone .post#" + postId + " > .inner-part > .status-line .unlike").addClass("hidden");
402                 $("#sone .post#" + postId + " > .inner-part > .status-line .like").removeClass("hidden");
403                 updatePostLikes(postId);
404         }, function(xmlHttpRequest, textStatus, error) {
405                 /* ignore error. */
406         });
407 }
408
409 function updatePostLikes(postId) {
410         $.getJSON("getLikes.ajax", { "type": "post", "post": postId }, function(data, textStatus) {
411                 if ((data != null) && data.success) {
412                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes").toggleClass("hidden", data.likes == 0)
413                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes span.like-count").text(data.likes);
414                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes > span").attr("title", generateSoneList(data.sones));
415                 }
416         }, function(xmlHttpRequest, textStatus, error) {
417                 /* ignore error. */
418         });
419 }
420
421 function likeReply(replyId) {
422         $.getJSON("like.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data, textStatus) {
423                 if ((data == null) || !data.success) {
424                         return;
425                 }
426                 $("#sone .reply#" + replyId + " .status-line .like").addClass("hidden");
427                 $("#sone .reply#" + replyId + " .status-line .unlike").removeClass("hidden");
428                 updateReplyLikes(replyId);
429         }, function(xmlHttpRequest, textStatus, error) {
430                 /* ignore error. */
431         });
432 }
433
434 function unlikeReply(replyId) {
435         $.getJSON("unlike.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data, textStatus) {
436                 if ((data == null) || !data.success) {
437                         return;
438                 }
439                 $("#sone .reply#" + replyId + " .status-line .unlike").addClass("hidden");
440                 $("#sone .reply#" + replyId + " .status-line .like").removeClass("hidden");
441                 updateReplyLikes(replyId);
442         }, function(xmlHttpRequest, textStatus, error) {
443                 /* ignore error. */
444         });
445 }
446
447 /**
448  * Trusts the Sone with the given ID.
449  *
450  * @param soneId
451  *            The ID of the Sone to trust
452  */
453 function trustSone(soneId) {
454         $.getJSON("trustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
455                 if ((data != null) && data.success) {
456                         updateTrustControls(soneId, data.trustValue);
457                 }
458         });
459 }
460
461 /**
462  * Distrusts the Sone with the given ID, i.e. assigns a negative trust value.
463  *
464  * @param soneId
465  *            The ID of the Sone to distrust
466  */
467 function distrustSone(soneId) {
468         $.getJSON("distrustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
469                 if ((data != null) && data.success) {
470                         updateTrustControls(soneId, data.trustValue);
471                 }
472         });
473 }
474
475 /**
476  * Untrusts the Sone with the given ID, i.e. removes any trust assignment.
477  *
478  * @param soneId
479  *            The ID of the Sone to untrust
480  */
481 function untrustSone(soneId) {
482         $.getJSON("untrustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
483                 if ((data != null) && data.success) {
484                         updateTrustControls(soneId, data.trustValue);
485                 }
486         });
487 }
488
489 /**
490  * Updates the trust controls for all posts and replies of the given Sone,
491  * according to the given trust value.
492  *
493  * @param soneId
494  *            The ID of the Sone to update all trust controls for
495  * @param trustValue
496  *            The trust value for the Sone
497  */
498 function updateTrustControls(soneId, trustValue) {
499         $("#sone .post").each(function() {
500                 if (getPostAuthor(this) == soneId) {
501                         getPostElement(this).find(".post-trust").toggleClass("hidden", trustValue != null);
502                         getPostElement(this).find(".post-distrust").toggleClass("hidden", trustValue != null);
503                         getPostElement(this).find(".post-untrust").toggleClass("hidden", trustValue == null);
504                 }
505         });
506         $("#sone .reply").each(function() {
507                 if (getReplyAuthor(this) == soneId) {
508                         getReplyElement(this).find(".reply-trust").toggleClass("hidden", trustValue != null);
509                         getReplyElement(this).find(".reply-distrust").toggleClass("hidden", trustValue != null);
510                         getReplyElement(this).find(".reply-untrust").toggleClass("hidden", trustValue == null);
511                 }
512         });
513 }
514
515 /**
516  * Bookmarks the post with the given ID.
517  *
518  * @param postId
519  *            The ID of the post to bookmark
520  */
521 function bookmarkPost(postId) {
522         (function(postId) {
523                 $.getJSON("bookmark.ajax", {"formPassword": getFormPassword(), "type": "post", "post": postId}, function(data, textStatus) {
524                         if ((data != null) && data.success) {
525                                 getPost(postId).find(".bookmark").toggleClass("hidden", true);
526                                 getPost(postId).find(".unbookmark").toggleClass("hidden", false);
527                         }
528                 });
529         })(postId);
530 }
531
532 /**
533  * Unbookmarks the post with the given ID.
534  *
535  * @param postId
536  *            The ID of the post to unbookmark
537  */
538 function unbookmarkPost(postId) {
539         $.getJSON("unbookmark.ajax", {"formPassword": getFormPassword(), "type": "post", "post": postId}, function(data, textStatus) {
540                 if ((data != null) && data.success) {
541                         getPost(postId).find(".bookmark").toggleClass("hidden", false);
542                         getPost(postId).find(".unbookmark").toggleClass("hidden", true);
543                 }
544         });
545 }
546
547 function updateReplyLikes(replyId) {
548         $.getJSON("getLikes.ajax", { "type": "reply", "reply": replyId }, function(data, textStatus) {
549                 if ((data != null) && data.success) {
550                         $("#sone .reply#" + replyId + " .status-line .likes").toggleClass("hidden", data.likes == 0)
551                         $("#sone .reply#" + replyId + " .status-line .likes span.like-count").text(data.likes);
552                         $("#sone .reply#" + replyId + " .status-line .likes > span").attr("title", generateSoneList(data.sones));
553                 }
554         }, function(xmlHttpRequest, textStatus, error) {
555                 /* ignore error. */
556         });
557 }
558
559 /**
560  * Posts a reply and calls the given callback when the request finishes.
561  *
562  * @param sender
563  *            The ID of the sender
564  * @param postId
565  *            The ID of the post the reply refers to
566  * @param text
567  *            The text to post
568  * @param callbackFunction
569  *            The callback function to call when the request finishes (takes 3
570  *            parameters: success, error, replyId)
571  */
572 function postReply(sender, postId, text, callbackFunction) {
573         $.getJSON("createReply.ajax", { "formPassword" : getFormPassword(), "sender": sender, "post" : postId, "text": text }, function(data, textStatus) {
574                 if (data == null) {
575                         /* TODO - show error */
576                         return;
577                 }
578                 if (data.success) {
579                         callbackFunction(true, null, data.reply, data.sone);
580                 } else {
581                         callbackFunction(false, data.error);
582                 }
583         }, function(xmlHttpRequest, textStatus, error) {
584                 /* ignore error. */
585         });
586 }
587
588 /**
589  * Ajaxifies the given Sone by enhancing all eligible elements with AJAX.
590  *
591  * @param soneElement
592  *            The Sone to ajaxify
593  */
594 function ajaxifySone(soneElement) {
595         /*
596          * convert all “follow”, “unfollow”, “lock”, and “unlock” links to something
597          * nicer.
598          */
599         $(".follow", soneElement).submit(function() {
600                 var followElement = this;
601                 $.getJSON("followSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
602                         $(followElement).addClass("hidden");
603                         $(followElement).parent().find(".unfollow").removeClass("hidden");
604                 });
605                 return false;
606         });
607         $(".unfollow", soneElement).submit(function() {
608                 var unfollowElement = this;
609                 $.getJSON("unfollowSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
610                         $(unfollowElement).addClass("hidden");
611                         $(unfollowElement).parent().find(".follow").removeClass("hidden");
612                 });
613                 return false;
614         });
615         $(".lock", soneElement).submit(function() {
616                 var lockElement = this;
617                 $.getJSON("lockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
618                         $(lockElement).addClass("hidden");
619                         $(lockElement).parent().find(".unlock").removeClass("hidden");
620                 });
621                 return false;
622         });
623         $(".unlock", soneElement).submit(function() {
624                 var unlockElement = this;
625                 $.getJSON("unlockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
626                         $(unlockElement).addClass("hidden");
627                         $(unlockElement).parent().find(".lock").removeClass("hidden");
628                 });
629                 return false;
630         });
631
632         /* mark Sone as known when clicking it. */
633         $(soneElement).click(function() {
634                 markSoneAsKnown(soneElement);
635         });
636 }
637
638 /**
639  * Ajaxifies the given post by enhancing all eligible elements with AJAX.
640  *
641  * @param postElement
642  *            The post element to ajaxify
643  */
644 function ajaxifyPost(postElement) {
645         $(postElement).find("form").submit(function() {
646                 return false;
647         });
648         $(postElement).find(".create-reply button:submit").click(function() {
649                 button = $(this);
650                 button.attr("disabled", "disabled");
651                 sender = $(this.form).find(":input[name=sender]").val();
652                 inputField = $(this.form).find(":input[name=text]:enabled").get(0);
653                 postId = getPostId(this);
654                 text = $(inputField).val();
655                 (function(sender, postId, text, inputField) {
656                         postReply(sender, postId, text, function(success, error, replyId, soneId) {
657                                 if (success) {
658                                         $(inputField).val("");
659                                         loadNewReply(replyId, soneId, postId);
660                                         $("#sone .post#" + postId + " .create-reply").addClass("hidden");
661                                         $("#sone .post#" + postId + " .create-reply .sender").hide();
662                                         $("#sone .post#" + postId + " .create-reply .select-sender").show();
663                                         $("#sone .post#" + postId + " .create-reply :input[name=sender]").val(getCurrentSoneId());
664                                 } else {
665                                         alert(error);
666                                 }
667                                 button.removeAttr("disabled");
668                         });
669                 })(sender, postId, text, inputField);
670                 return false;
671         });
672
673         /* replace all “delete” buttons with javascript. */
674         (function(postElement) {
675                 getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
676                         postId = getPostId(postElement);
677                         enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
678                 });
679         })(postElement);
680
681         /* convert all “like” buttons to javascript functions. */
682         $(postElement).find(".like-post").submit(function() {
683                 likePost(getPostId(this));
684                 return false;
685         });
686         $(postElement).find(".unlike-post").submit(function() {
687                 unlikePost(getPostId(this));
688                 return false;
689         });
690
691         /* convert trust control buttons to javascript functions. */
692         $(postElement).find(".post-trust").submit(function() {
693                 trustSone(getPostAuthor(this));
694                 return false;
695         });
696         $(postElement).find(".post-distrust").submit(function() {
697                 distrustSone(getPostAuthor(this));
698                 return false;
699         });
700         $(postElement).find(".post-untrust").submit(function() {
701                 untrustSone(getPostAuthor(this));
702                 return false;
703         });
704
705         /* convert bookmark/unbookmark buttons to javascript functions. */
706         $(postElement).find(".bookmark").submit(function() {
707                 bookmarkPost(getPostId(this));
708                 return false;
709         });
710         $(postElement).find(".unbookmark").submit(function() {
711                 unbookmarkPost(getPostId(this));
712                 return false;
713         });
714
715         /* convert “show source” link into javascript function. */
716         $(postElement).find(".show-source").each(function() {
717                 $("a", this).click(function() {
718                         $(".post-text.text", getPostElement(this)).toggleClass("hidden");
719                         $(".post-text.raw-text", getPostElement(this)).toggleClass("hidden");
720                         return false;
721                 });
722         });
723
724         /* add “comment” link. */
725         addCommentLink(getPostId(postElement), postElement, $(postElement).find(".post-status-line .time"));
726
727         /* process all replies. */
728         replyIds = [];
729         $(postElement).find(".reply").each(function() {
730                 replyIds.push(getReplyId(this));
731                 ajaxifyReply(this);
732         });
733         updateReplyTimes(replyIds.join(","));
734
735         /* process reply input fields. */
736         getTranslation("WebInterface.DefaultText.Reply", function(text) {
737                 $(postElement).find("input.reply-input").each(function() {
738                         registerInputTextareaSwap(this, text, "text", false, false);
739                 });
740         });
741
742         /* process sender selection. */
743         $(".select-sender", postElement).css("display", "inline");
744         $(".sender", postElement).hide();
745         $(".select-sender button", postElement).click(function() {
746                 $(".sender", postElement).show();
747                 $(".select-sender", postElement).hide();
748                 return false;
749         });
750
751         /* mark everything as known on click. */
752         $(postElement).click(function(event) {
753                 if ($(event.target).hasClass("click-to-show")) {
754                         return false;
755                 }
756                 markPostAsKnown(this);
757         });
758
759         /* hide reply input field. */
760         $(postElement).find(".create-reply").addClass("hidden");
761 }
762
763 /**
764  * Ajaxifies the given reply element.
765  *
766  * @param replyElement
767  *            The reply element to ajaxify
768  */
769 function ajaxifyReply(replyElement) {
770         $(replyElement).find(".like-reply").submit(function() {
771                 likeReply(getReplyId(this));
772                 return false;
773         });
774         $(replyElement).find(".unlike-reply").submit(function() {
775                 unlikeReply(getReplyId(this));
776                 return false;
777         });
778         (function(replyElement) {
779                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
780                         $(replyElement).find(".delete-reply button").each(function() {
781                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
782                         });
783                 });
784         })(replyElement);
785         addCommentLink(getPostId(replyElement), replyElement, $(replyElement).find(".reply-status-line .time"));
786
787         /* convert “show source” link into javascript function. */
788         $(replyElement).find(".show-reply-source").each(function() {
789                 $("a", this).click(function() {
790                         $(".reply-text.text", getReplyElement(this)).toggleClass("hidden");
791                         $(".reply-text.raw-text", getReplyElement(this)).toggleClass("hidden");
792                         return false;
793                 });
794         });
795
796         /* convert trust control buttons to javascript functions. */
797         $(replyElement).find(".reply-trust").submit(function() {
798                 trustSone(getReplyAuthor(this));
799                 return false;
800         });
801         $(replyElement).find(".reply-distrust").submit(function() {
802                 distrustSone(getReplyAuthor(this));
803                 return false;
804         });
805         $(replyElement).find(".reply-untrust").submit(function() {
806                 untrustSone(getReplyAuthor(this));
807                 return false;
808         });
809 }
810
811 /**
812  * Ajaxifies the given notification by replacing the form with AJAX.
813  *
814  * @param notification
815  *            jQuery object representing the notification.
816  */
817 function ajaxifyNotification(notification) {
818         notification.find("form").submit(function() {
819                 return false;
820         });
821         notification.find("input[name=returnPage]").val($.url.attr("relative"));
822         if (notification.find(".short-text").length > 0) {
823                 notification.find(".short-text").removeClass("hidden");
824                 notification.find(".text").addClass("hidden");
825         }
826         notification.find("form.mark-as-read button").click(function() {
827                 $.getJSON("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": $(":input[name=type]", this.form).val(), "id": $(":input[name=id]", this.form).val()});
828         });
829         notification.find("a[class^='link-']").each(function() {
830                 linkElement = $(this);
831                 if (linkElement.is("[href^='viewPost']")) {
832                         id = linkElement.attr("class").substr(5);
833                         if (hasPost(id)) {
834                                 linkElement.attr("href", "#post-" + id);
835                         }
836                 }
837         });
838         notification.find("form.dismiss button").click(function() {
839                 $.getJSON("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.attr("id") }, function(data, textStatus) {
840                         /* dismiss in case of error, too. */
841                         notification.slideUp();
842                 }, function(xmlHttpRequest, textStatus, error) {
843                         /* ignore error. */
844                 });
845         });
846         return notification;
847 }
848
849 function getStatus() {
850         $.getJSON("getStatus.ajax", {"loadAllSones": isKnownSonesPage()}, function(data, textStatus) {
851                 if ((data != null) && data.success) {
852                         /* process Sone information. */
853                         $.each(data.sones, function(index, value) {
854                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdatedUnknown ? null : value.lastUpdated);
855                         });
856                         /* search for removed notifications. */
857                         $("#sone #notification-area .notification").each(function() {
858                                 notificationId = $(this).attr("id");
859                                 foundNotification = false;
860                                 $.each(data.notifications, function(index, value) {
861                                         if (value.id == notificationId) {
862                                                 foundNotification = true;
863                                                 return false;
864                                         }
865                                 });
866                                 if (!foundNotification) {
867                                         $(this).slideUp("normal", function() {
868                                                 $(this).remove();
869                                         });
870                                 }
871                         });
872                         /* process notifications. */
873                         $.each(data.notifications, function(index, value) {
874                                 oldNotification = $("#sone #notification-area .notification#" + value.id);
875                                 notification = ajaxifyNotification(createNotification(value.id, value.text, value.dismissable)).hide();
876                                 if (oldNotification.length != 0) {
877                                         if ((oldNotification.find(".short-text").length > 0) && (notification.find(".short-text").length > 0)) {
878                                                 opened = oldNotification.is(":visible") && oldNotification.find(".short-text").hasClass("hidden");
879                                                 notification.find(".short-text").toggleClass("hidden", opened);
880                                                 notification.find(".text").toggleClass("hidden", !opened);
881                                         }
882                                         oldNotification.replaceWith(notification.show());
883                                 } else {
884                                         $("#sone #notification-area").append(notification);
885                                         notification.slideDown();
886                                         setActivity();
887                                 }
888                         });
889                         /* process new posts. */
890                         $.each(data.newPosts, function(index, value) {
891                                 loadNewPost(value.id, value.sone, value.recipient, value.time);
892                         });
893                         /* process new replies. */
894                         $.each(data.newReplies, function(index, value) {
895                                 loadNewReply(value.id, value.sone, value.post, value.postSone);
896                         });
897                         /* do it again in 5 seconds. */
898                         setTimeout(getStatus, 5000);
899                 } else {
900                         /* data.success was false, wait 30 seconds. */
901                         setTimeout(getStatus, 30000);
902                 }
903         }, function(xmlHttpRequest, textStatus, error) {
904                 /* something really bad happend, wait a minute. */
905                 setTimeout(getStatus, 60000);
906         })
907 }
908
909 /**
910  * Returns the ID of the currently logged in Sone.
911  *
912  * @return The ID of the current Sone, or an empty string if no Sone is logged
913  *         in
914  */
915 function getCurrentSoneId() {
916         return $("#currentSoneId").text();
917 }
918
919 /**
920  * Returns the content of the page-id attribute.
921  *
922  * @returns The page ID
923  */
924 function getPageId() {
925         return $("#sone .page-id").text();
926 }
927
928 /**
929  * Returns whether the current page is the index page.
930  *
931  * @returns {Boolean} <code>true</code> if the current page is the index page,
932  *          <code>false</code> otherwise
933  */
934 function isIndexPage() {
935         return getPageId() == "index";
936 }
937
938 /**
939  * Returns whether the current page is a “view Sone” page.
940  *
941  * @returns {Boolean} <code>true</code> if the current page is a “view Sone”
942  *          page, <code>false</code> otherwise
943  */
944 function isViewSonePage() {
945         return getPageId() == "view-sone";
946 }
947
948 /**
949  * Returns the ID of the currently shown Sone. This will only return a sensible
950  * value if isViewSonePage() returns <code>true</code>.
951  *
952  * @returns The ID of the currently shown Sone
953  */
954 function getShownSoneId() {
955         return $("#sone .sone-id").text();
956 }
957
958 /**
959  * Returns whether the current page is a “view post” page.
960  *
961  * @returns {Boolean} <code>true</code> if the current page is a “view post”
962  *          page, <code>false</code> otherwise
963  */
964 function isViewPostPage() {
965         return getPageId() == "view-post";
966 }
967
968 /**
969  * Returns the ID of the currently shown post. This will only return a sensible
970  * value if isViewPostPage() returns <code>true</code>.
971  *
972  * @returns The ID of the currently shown post
973  */
974 function getShownPostId() {
975         return $("#sone .post-id").text();
976 }
977
978 /**
979  * Returns whether the current page is the “known Sones” page.
980  *
981  * @returns {Boolean} <code>true</code> if the current page is the “known
982  *          Sones” page, <code>false</code> otherwise
983  */
984 function isKnownSonesPage() {
985         return getPageId() == "known-sones";
986 }
987
988 /**
989  * Returns whether a post with the given ID exists on the current page.
990  *
991  * @param postId
992  *            The post ID to check for
993  * @returns {Boolean} <code>true</code> if a post with the given ID already
994  *          exists on the page, <code>false</code> otherwise
995  */
996 function hasPost(postId) {
997         return $(".post#" + postId).length > 0;
998 }
999
1000 /**
1001  * Returns whether a reply with the given ID exists on the current page.
1002  *
1003  * @param replyId
1004  *            The reply ID to check for
1005  * @returns {Boolean} <code>true</code> if a reply with the given ID already
1006  *          exists on the page, <code>false</code> otherwise
1007  */
1008 function hasReply(replyId) {
1009         return $("#sone .reply#" + replyId).length > 0;
1010 }
1011
1012 function loadNewPost(postId, soneId, recipientId, time) {
1013         if (hasPost(postId)) {
1014                 return;
1015         }
1016         if (!isIndexPage()) {
1017                 if (!isViewPostPage() || (getShownPostId() != postId)) {
1018                         if (!isViewSonePage() || ((getShownSoneId() != soneId) && (getShownSoneId() != recipientId))) {
1019                                 return;
1020                         }
1021                 }
1022         }
1023         if (getPostTime($("#sone .post").last()) > time) {
1024                 return;
1025         }
1026         $.getJSON("getPost.ajax", { "post" : postId }, function(data, textStatus) {
1027                 if ((data != null) && data.success) {
1028                         if (hasPost(data.post.id)) {
1029                                 return;
1030                         }
1031                         if (!isIndexPage() && !(isViewSonePage() && ((getShownSoneId() == data.post.sone) || (getShownSoneId() == data.post.recipient)))) {
1032                                 return;
1033                         }
1034                         var firstOlderPost = null;
1035                         $("#sone .post").each(function() {
1036                                 if (getPostTime(this) < data.post.time) {
1037                                         firstOlderPost = $(this);
1038                                         return false;
1039                                 }
1040                         });
1041                         newPost = $(data.post.html).addClass("hidden");
1042                         if (firstOlderPost != null) {
1043                                 newPost.insertBefore(firstOlderPost);
1044                         }
1045                         ajaxifyPost(newPost);
1046                         updatePostTimes(data.post.id);
1047                         newPost.slideDown();
1048                         setActivity();
1049                 }
1050         });
1051 }
1052
1053 function loadNewReply(replyId, soneId, postId, postSoneId) {
1054         if (hasReply(replyId)) {
1055                 return;
1056         }
1057         if (!hasPost(postId)) {
1058                 return;
1059         }
1060         $.getJSON("getReply.ajax", { "reply": replyId }, function(data, textStatus) {
1061                 /* find post. */
1062                 if ((data != null) && data.success) {
1063                         if (hasReply(data.reply.id)) {
1064                                 return;
1065                         }
1066                         $("#sone .post#" + data.reply.postId).each(function() {
1067                                 var firstNewerReply = null;
1068                                 $(this).find(".replies .reply").each(function() {
1069                                         if (getReplyTime(this) > data.reply.time) {
1070                                                 firstNewerReply = $(this);
1071                                                 return false;
1072                                         }
1073                                 });
1074                                 newReply = $(data.reply.html).addClass("hidden");
1075                                 if (firstNewerReply != null) {
1076                                         newReply.insertBefore(firstNewerReply);
1077                                 } else {
1078                                         if ($(this).find(".replies .create-reply")) {
1079                                                 $(this).find(".replies .create-reply").before(newReply);
1080                                         } else {
1081                                                 $(this).find(".replies").append(newReply);
1082                                         }
1083                                 }
1084                                 ajaxifyReply(newReply);
1085                                 updateReplyTimes(data.reply.id);
1086                                 newReply.slideDown();
1087                                 setActivity();
1088                                 return false;
1089                         });
1090                 }
1091         });
1092 }
1093
1094 /**
1095  * Marks the given Sone as known if it is still new.
1096  *
1097  * @param soneElement
1098  *            The Sone to mark as known
1099  */
1100 function markSoneAsKnown(soneElement) {
1101         if ($(".new", soneElement).length > 0) {
1102                 $.getJSON("maskAsKnown.ajax", {"formPassword": getFormPassword(), "type": "sone", "id": getSoneId(soneElement)}, function(data, textStatus) {
1103                         $(soneElement).removeClass("new");
1104                 });
1105         }
1106 }
1107
1108 function markPostAsKnown(postElements) {
1109         $(postElements).each(function() {
1110                 postElement = this;
1111                 if ($(postElement).hasClass("new")) {
1112                         (function(postElement) {
1113                                 $(postElement).removeClass("new");
1114                                 $(".click-to-show", postElement).removeClass("new");
1115                                 $.getJSON("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "post", "id": getPostId(postElement)});
1116                         })(postElement);
1117                 }
1118         });
1119         markReplyAsKnown($(postElements).find(".reply"));
1120 }
1121
1122 function markReplyAsKnown(replyElements) {
1123         $(replyElements).each(function() {
1124                 replyElement = this;
1125                 if ($(replyElement).hasClass("new")) {
1126                         (function(replyElement) {
1127                                 $(replyElement).removeClass("new");
1128                                 $.getJSON("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "reply", "id": getReplyId(replyElement)});
1129                         })(replyElement);
1130                 }
1131         });
1132 }
1133
1134 /**
1135  * Updates the time of the post with the given ID.
1136  *
1137  * @param postId
1138  *            The ID of the post to update
1139  * @param timeText
1140  *            The text of the time to show
1141  * @param refreshTime
1142  *            The refresh time after which to request a new time (in seconds)
1143  * @param tooltip
1144  *            The tooltip to show
1145  */
1146 function updatePostTime(postId, timeText, refreshTime, tooltip) {
1147         if (!getPost(postId).is(":visible")) {
1148                 return;
1149         }
1150         getPost(postId).find(".post-status-line > .time a").html(timeText).attr("title", tooltip);
1151         (function(postId, refreshTime) {
1152                 setTimeout(function() {
1153                         updatePostTimes(postId);
1154                 }, refreshTime * 1000);
1155         })(postId, refreshTime);
1156 }
1157
1158 /**
1159  * Requests new rendered times for the posts with the given IDs.
1160  *
1161  * @param postIds
1162  *            Comma-separated post IDs
1163  */
1164 function updatePostTimes(postIds) {
1165         $.getJSON("getTimes.ajax", { "posts" : postIds }, function(data, textStatus) {
1166                 if ((data != null) && data.success) {
1167                         $.each(data.postTimes, function(index, value) {
1168                                 updatePostTime(index, value.timeText, value.refreshTime, value.tooltip);
1169                         });
1170                 }
1171         });
1172 }
1173
1174 /**
1175  * Updates the time of the reply with the given ID.
1176  *
1177  * @param postId
1178  *            The ID of the reply to update
1179  * @param timeText
1180  *            The text of the time to show
1181  * @param refreshTime
1182  *            The refresh time after which to request a new time (in seconds)
1183  * @param tooltip
1184  *            The tooltip to show
1185  */
1186 function updateReplyTime(replyId, timeText, refreshTime, tooltip) {
1187         if (!getReply(replyId).is(":visible")) {
1188                 return;
1189         }
1190         getReply(replyId).find(".reply-status-line > .time").html(timeText).attr("title", tooltip);
1191         (function(replyId, refreshTime) {
1192                 setTimeout(function() {
1193                         updateReplyTimes(replyId);
1194                 }, refreshTime * 1000);
1195         })(replyId, refreshTime);
1196 }
1197
1198 /**
1199  * Requests new rendered times for the posts with the given IDs.
1200  *
1201  * @param postIds
1202  *            Comma-separated post IDs
1203  */
1204 function updateReplyTimes(replyIds) {
1205         $.getJSON("getTimes.ajax", { "replies" : replyIds }, function(data, textStatus) {
1206                 if ((data != null) && data.success) {
1207                         $.each(data.replyTimes, function(index, value) {
1208                                 updateReplyTime(index, value.timeText, value.refreshTime, value.tooltip);
1209                         });
1210                 }
1211         });
1212 }
1213
1214 function resetActivity() {
1215         title = document.title;
1216         if (title.indexOf('(') == 0) {
1217                 setTitle(title.substr(title.indexOf(' ') + 1));
1218         }
1219 }
1220
1221 function setActivity() {
1222         if (!focus) {
1223                 title = document.title;
1224                 if (title.indexOf('(') != 0) {
1225                         setTitle("(!) " + title);
1226                 }
1227                 if (!iconBlinking) {
1228                         setTimeout(toggleIcon, 1500);
1229                         iconBlinking = true;
1230                 }
1231         }
1232 }
1233
1234 /**
1235  * Sets the window title after a small delay to prevent race-condition issues.
1236  *
1237  * @param title
1238  *            The title to set
1239  */
1240 function setTitle(title) {
1241         setTimeout(function() {
1242                 document.title = title;
1243         }, 50);
1244 }
1245
1246 /** Whether the icon is currently showing activity. */
1247 var iconActive = false;
1248
1249 /** Whether the icon is currently supposed to blink. */
1250 var iconBlinking = false;
1251
1252 /**
1253  * Toggles the icon. If the window has gained focus and the icon is still
1254  * showing the activity state, it is returned to normal.
1255  */
1256 function toggleIcon() {
1257         if (focus) {
1258                 if (iconActive) {
1259                         changeIcon("images/icon.png");
1260                         iconActive = false;
1261                 }
1262                 iconBlinking = false;
1263         } else {
1264                 iconActive = !iconActive;
1265                 changeIcon(iconActive ? "images/icon-activity.png" : "images/icon.png");
1266                 setTimeout(toggleIcon, 1500);
1267         }
1268 }
1269
1270 /**
1271  * Changes the icon of the page.
1272  *
1273  * @param iconUrl
1274  *            The new URL of the icon
1275  */
1276 function changeIcon(iconUrl) {
1277         $("link[rel=icon]").remove();
1278         $("head").append($("<link>").attr("rel", "icon").attr("type", "image/png").attr("href", iconUrl));
1279         $("iframe[id=icon-update]")[0].src += "";
1280 }
1281
1282 /**
1283  * Creates a new notification.
1284  *
1285  * @param id
1286  *            The ID of the notificaiton
1287  * @param text
1288  *            The text of the notification
1289  * @param dismissable
1290  *            <code>true</code> if the notification can be dismissed by the
1291  *            user
1292  */
1293 function createNotification(id, text, dismissable) {
1294         notification = $("<div></div>").addClass("notification").attr("id", id);
1295         if (dismissable) {
1296                 dismissForm = $("#sone #notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id")
1297                 dismissForm.find("input[name=notification]").val(id);
1298                 notification.append(dismissForm);
1299         }
1300         notification.append(text);
1301         return notification;
1302 }
1303
1304 /**
1305  * Shows the details of the notification with the given ID.
1306  *
1307  * @param notificationId
1308  *            The ID of the notification
1309  */
1310 function showNotificationDetails(notificationId) {
1311         $("#sone .notification#" + notificationId + " .text").removeClass("hidden");
1312         $("#sone .notification#" + notificationId + " .short-text").addClass("hidden");
1313 }
1314
1315 /**
1316  * Deletes the field with the given ID from the profile.
1317  *
1318  * @param fieldId
1319  *            The ID of the field to delete
1320  */
1321 function deleteProfileField(fieldId) {
1322         $.getJSON("deleteProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId}, function(data, textStatus) {
1323                 if (data && data.success) {
1324                         $("#sone .profile-field#" + data.field.id).slideUp();
1325                 }
1326         });
1327 }
1328
1329 /**
1330  * Renames a profile field.
1331  *
1332  * @param fieldId
1333  *            The ID of the field to rename
1334  * @param newName
1335  *            The new name of the field
1336  * @param successFunction
1337  *            Called when the renaming was successful
1338  */
1339 function editProfileField(fieldId, newName, successFunction) {
1340         $.getJSON("editProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "name": newName}, function(data, textStatus) {
1341                 if (data && data.success) {
1342                         successFunction();
1343                 }
1344         });
1345 }
1346
1347 /**
1348  * Moves the profile field with the given ID one slot in the given direction.
1349  *
1350  * @param fieldId
1351  *            The ID of the field to move
1352  * @param direction
1353  *            The direction to move in (“up” or “down”)
1354  * @param successFunction
1355  *            Function to call on success
1356  */
1357 function moveProfileField(fieldId, direction, successFunction) {
1358         $.getJSON("moveProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "direction": direction}, function(data, textStatus) {
1359                 if (data && data.success) {
1360                         successFunction();
1361                 }
1362         });
1363 }
1364
1365 /**
1366  * Moves the profile field with the given ID up one slot.
1367  *
1368  * @param fieldId
1369  *            The ID of the field to move
1370  * @param successFunction
1371  *            Function to call on success
1372  */
1373 function moveProfileFieldUp(fieldId, successFunction) {
1374         moveProfileField(fieldId, "up", successFunction);
1375 }
1376
1377 /**
1378  * Moves the profile field with the given ID down one slot.
1379  *
1380  * @param fieldId
1381  *            The ID of the field to move
1382  * @param successFunction
1383  *            Function to call on success
1384  */
1385 function moveProfileFieldDown(fieldId, successFunction) {
1386         moveProfileField(fieldId, "down", successFunction);
1387 }
1388
1389 //
1390 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
1391 //
1392
1393 var focus = true;
1394
1395 $(document).ready(function() {
1396
1397         /* this initializes the status update input field. */
1398         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
1399                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
1400                 $("#sone #update-status .select-sender").css("display", "inline");
1401                 $("#sone #update-status .sender").hide();
1402                 $("#sone #update-status .select-sender button").click(function() {
1403                         $("#sone #update-status .sender").show();
1404                         $("#sone #update-status .select-sender").hide();
1405                         return false;
1406                 });
1407                 $("#sone #update-status").submit(function() {
1408                         button = $("button:submit", this);
1409                         button.attr("disabled", "disabled");
1410                         if ($(this).find(":input.default:enabled").length > 0) {
1411                                 return false;
1412                         }
1413                         sender = $(this).find(":input[name=sender]").val();
1414                         text = $(this).find(":input[name=text]:enabled").val();
1415                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "sender": sender, "text": text }, function(data, textStatus) {
1416                                 if ((data != null) && data.success) {
1417                                         loadNewPost(data.postId, data.sone, data.recipient);
1418                                 }
1419                                 button.removeAttr("disabled");
1420                         });
1421                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1422                         $(this).find(":input[name=text]:enabled").val("").blur();
1423                         $(this).find(".sender").hide();
1424                         $(this).find(".select-sender").show();
1425                         return false;
1426                 });
1427         });
1428
1429         /* ajaxify the search input field. */
1430         getTranslation("WebInterface.DefaultText.Search", function(defaultText) {
1431                 registerInputTextareaSwap("#sone #search input[name=query]", defaultText, "query", false, true);
1432         });
1433
1434         /* ajaxify input field on “view Sone” page. */
1435         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
1436                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
1437                 $("#sone #post-message .select-sender").css("display", "inline");
1438                 $("#sone #post-message .sender").hide();
1439                 $("#sone #post-message .select-sender button").click(function() {
1440                         $("#sone #post-message .sender").show();
1441                         $("#sone #post-message .select-sender").hide();
1442                         return false;
1443                 });
1444                 $("#sone #post-message").submit(function() {
1445                         sender = $(this).find(":input[name=sender]").val();
1446                         text = $(this).find(":input[name=text]:enabled").val();
1447                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "sender": sender, "text": text }, function(data, textStatus) {
1448                                 if ((data != null) && data.success) {
1449                                         loadNewPost(data.postId, getCurrentSoneId());
1450                                 }
1451                         });
1452                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1453                         $(this).find(":input[name=text]:enabled").val("").blur();
1454                         $(this).find(".sender").hide();
1455                         $(this).find(".select-sender").show();
1456                         return false;
1457                 });
1458         });
1459
1460         /* Ajaxifies all posts. */
1461         /* calling getTranslation here will cache the necessary values. */
1462         getTranslation("WebInterface.Confirmation.DeletePostButton", function(text) {
1463                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(text) {
1464                         getTranslation("WebInterface.DefaultText.Reply", function(text) {
1465                                 $("#sone .post").each(function() {
1466                                         ajaxifyPost(this);
1467                                 });
1468                         });
1469                 });
1470         });
1471
1472         /* update post times. */
1473         postIds = [];
1474         $("#sone .post").each(function() {
1475                 postIds.push(getPostId(this));
1476         });
1477         updatePostTimes(postIds.join(","));
1478
1479         /* hides all replies but the latest two. */
1480         if (!isViewPostPage()) {
1481                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
1482                         $("#sone .post .replies").each(function() {
1483                                 allReplies = $(this).find(".reply");
1484                                 if (allReplies.length > 2) {
1485                                         newHidden = false;
1486                                         for (replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1487                                                 $(allReplies[replyIndex]).addClass("hidden");
1488                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1489                                         }
1490                                         clickToShowElement = $("<div></div>").addClass("click-to-show");
1491                                         if (newHidden) {
1492                                                 clickToShowElement.addClass("new");
1493                                         }
1494                                         (function(clickToShowElement, allReplies, text) {
1495                                                 clickToShowElement.text(text);
1496                                                 clickToShowElement.click(function() {
1497                                                         allReplies.removeClass("hidden");
1498                                                         clickToShowElement.addClass("hidden");
1499                                                 });
1500                                         })(clickToShowElement, allReplies, text);
1501                                         $(allReplies[0]).before(clickToShowElement);
1502                                 }
1503                         });
1504                 });
1505         }
1506
1507         $("#sone .sone").each(function() {
1508                 ajaxifySone($(this));
1509         });
1510
1511         /* process all existing notifications, ajaxify dismiss buttons. */
1512         $("#sone #notification-area .notification").each(function() {
1513                 ajaxifyNotification($(this));
1514         });
1515
1516         /* activate status polling. */
1517         setTimeout(getStatus, 5000);
1518
1519         /* reset activity counter when the page has focus. */
1520         $(window).focus(function() {
1521                 focus = true;
1522                 resetActivity();
1523         }).blur(function() {
1524                 focus = false;
1525         })
1526
1527 });