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