Merge branch 'message-recipient'
[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                                 textarea.show().focus();
41                         });
42                         if (inputField.val() == "") {
43                                 inputField.addClass("default");
44                                 inputField.val(defaultText);
45                         } else {
46                                 inputField.hide().attr("disabled", "disabled");
47                                 textarea.show();
48                         }
49                         $(inputField.get(0).form).submit(function() {
50                                 if (!optional && (textarea.val() == "")) {
51                                         return false;
52                                 }
53                         });
54                 })($(this), textarea);
55         });
56 }
57
58 /**
59  * Adds a “comment” link to all status lines contained in the given element.
60  *
61  * @param postId
62  *            The ID of the post
63  * @param element
64  *            The element to add a “comment” link to
65  */
66 function addCommentLink(postId, element, insertAfterThisElement) {
67         if ($(element).find(".show-reply-form").length > 0) {
68                 return;
69         }
70         commentElement = (function(postId) {
71                 var commentElement = $("<div><span>Comment</span></div>").addClass("show-reply-form").click(function() {
72                         markPostAsKnown(getPostElement(this));
73                         replyElement = $("#sone .post#" + postId + " .create-reply");
74                         replyElement.removeClass("hidden");
75                         replyElement.removeClass("light");
76                         (function(replyElement) {
77                                 replyElement.find("input.reply-input").blur(function() {
78                                         if ($(this).hasClass("default")) {
79                                                 replyElement.addClass("light");
80                                         }
81                                 }).focus(function() {
82                                         replyElement.removeClass("light");
83                                 });
84                         })(replyElement);
85                         replyElement.find("input.reply-input").focus();
86                 });
87                 return commentElement;
88         })(postId);
89         $(insertAfterThisElement).after(commentElement.clone(true));
90 }
91
92 var translations = {};
93
94 /**
95  * Retrieves the translation for the given key and calls the callback function.
96  * The callback function takes a single parameter, the translated string.
97  *
98  * @param key
99  *            The key of the translation string
100  * @param callback
101  *            The callback function
102  */
103 function getTranslation(key, callback) {
104         if (key in translations) {
105                 callback(translations[key]);
106                 return;
107         }
108         $.getJSON("getTranslation.ajax", {"key": key}, function(data, textStatus) {
109                 if ((data != null) && data.success) {
110                         translations[key] = data.value;
111                         callback(data.value);
112                 }
113         }, function(xmlHttpRequest, textStatus, error) {
114                 /* ignore error. */
115         });
116 }
117
118 /**
119  * Filters the given Sone ID, replacing all “~” characters by an underscore.
120  *
121  * @param soneId
122  *            The Sone ID to filter
123  * @returns The filtered Sone ID
124  */
125 function filterSoneId(soneId) {
126         return soneId.replace(/[^a-zA-Z0-9-]/g, "_");
127 }
128
129 /**
130  * Updates the status of the given Sone.
131  *
132  * @param soneId
133  *            The ID of the Sone to update
134  * @param status
135  *            The status of the Sone (“idle”, “unknown”, “inserting”,
136  *            “downloading”)
137  * @param modified
138  *            Whether the Sone is modified
139  * @param locked
140  *            Whether the Sone is locked
141  * @param lastUpdated
142  *            The date and time of the last update (formatted for display)
143  */
144 function updateSoneStatus(soneId, name, status, modified, locked, lastUpdated) {
145         $("#sone .sone." + filterSoneId(soneId)).
146                 toggleClass("unknown", status == "unknown").
147                 toggleClass("idle", status == "idle").
148                 toggleClass("inserting", status == "inserting").
149                 toggleClass("downloading", status == "downloading").
150                 toggleClass("modified", modified);
151         $("#sone .sone." + filterSoneId(soneId) + " .lock").toggleClass("hidden", locked);
152         $("#sone .sone." + filterSoneId(soneId) + " .unlock").toggleClass("hidden", !locked);
153         $("#sone .sone." + filterSoneId(soneId) + " .last-update span.time").text(lastUpdated);
154         $("#sone .sone." + filterSoneId(soneId) + " .profile-link a").text(name);
155 }
156
157 /**
158  * Enhances a “delete” button so that the confirmation is done on the same page.
159  *
160  * @param button
161  *            The button element
162  * @param text
163  *            The text to show on the button
164  * @param deleteCallback
165  *            The callback that actually deletes something
166  */
167 function enhanceDeleteButton(button, text, deleteCallback) {
168         (function(button) {
169                 newButton = $("<button></button>").addClass("confirm").hide().text(text).click(function() {
170                         $(this).fadeOut("slow");
171                         deleteCallback();
172                         return false;
173                 }).insertAfter(button);
174                 (function(button, newButton) {
175                         button.click(function() {
176                                 button.fadeOut("slow", function() {
177                                         newButton.fadeIn("slow");
178                                         $(document).one("click", function() {
179                                                 if (this != newButton.get(0)) {
180                                                         newButton.fadeOut(function() {
181                                                                 button.fadeIn();
182                                                         });
183                                                 }
184                                         });
185                                 });
186                                 return false;
187                         });
188                 })(button, newButton);
189         })($(button));
190 }
191
192 /**
193  * Enhances a post’s “delete” button.
194  *
195  * @param button
196  *            The button element
197  * @param postId
198  *            The ID of the post to delete
199  * @param text
200  *            The text to replace the button with
201  */
202 function enhanceDeletePostButton(button, postId, text) {
203         enhanceDeleteButton(button, text, function() {
204                 $.getJSON("deletePost.ajax", { "post": postId, "formPassword": getFormPassword() }, function(data, textStatus) {
205                         if (data == null) {
206                                 return;
207                         }
208                         if (data.success) {
209                                 $("#sone .post#" + postId).slideUp();
210                         } else if (data.error == "invalid-post-id") {
211                                 alert("Invalid post ID given!");
212                         } else if (data.error == "auth-required") {
213                                 alert("You need to be logged in.");
214                         } else if (data.error == "not-authorized") {
215                                 alert("You are not allowed to delete this post.");
216                         }
217                 }, function(xmlHttpRequest, textStatus, error) {
218                         /* ignore error. */
219                 });
220         });
221 }
222
223 /**
224  * Enhances a reply’s “delete” button.
225  *
226  * @param button
227  *            The button element
228  * @param replyId
229  *            The ID of the reply to delete
230  * @param text
231  *            The text to replace the button with
232  */
233 function enhanceDeleteReplyButton(button, replyId, text) {
234         enhanceDeleteButton(button, text, function() {
235                 $.getJSON("deleteReply.ajax", { "reply": replyId, "formPassword": $("#sone #formPassword").text() }, function(data, textStatus) {
236                         if (data == null) {
237                                 return;
238                         }
239                         if (data.success) {
240                                 $("#sone .reply#" + replyId).slideUp();
241                         } else if (data.error == "invalid-reply-id") {
242                                 alert("Invalid reply ID given!");
243                         } else if (data.error == "auth-required") {
244                                 alert("You need to be logged in.");
245                         } else if (data.error == "not-authorized") {
246                                 alert("You are not allowed to delete this reply.");
247                         }
248                 }, function(xmlHttpRequest, textStatus, error) {
249                         /* ignore error. */
250                 });
251         });
252 }
253
254 function getFormPassword() {
255         return $("#sone #formPassword").text();
256 }
257
258 function getSoneElement(element) {
259         return $(element).parents(".sone");
260 }
261
262 /**
263  * Generates a list of Sones by concatening the names of the given sones with a
264  * new line character (“\n”).
265  *
266  * @param sones
267  *            The sones to format
268  * @returns {String} The created string
269  */
270 function generateSoneList(sones) {
271         var soneList = "";
272         $.each(sones, function() {
273                 if (soneList != "") {
274                         soneList += ", ";
275                 }
276                 soneList += this.name;
277         });
278         return soneList;
279 }
280
281 /**
282  * Returns the ID of the Sone that this element belongs to.
283  *
284  * @param element
285  *            The element to locate the matching Sone ID for
286  * @returns The ID of the Sone, or undefined
287  */
288 function getSoneId(element) {
289         return getSoneElement(element).find(".id").text();
290 }
291
292 function getPostElement(element) {
293         return $(element).closest(".post");
294 }
295
296 function getPostId(element) {
297         return getPostElement(element).attr("id");
298 }
299
300 function getPostTime(element) {
301         return getPostElement(element).find(".post-time").text();
302 }
303
304 function getReplyElement(element) {
305         return $(element).closest(".reply");
306 }
307
308 function getReplyId(element) {
309         return getReplyElement(element).attr("id");
310 }
311
312 function getReplyTime(element) {
313         return getReplyElement(element).find(".reply-time").text();
314 }
315
316 function likePost(postId) {
317         $.getJSON("like.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
318                 if ((data == null) || !data.success) {
319                         return;
320                 }
321                 $("#sone .post#" + postId + " > .inner-part > .status-line .like").addClass("hidden");
322                 $("#sone .post#" + postId + " > .inner-part > .status-line .unlike").removeClass("hidden");
323                 updatePostLikes(postId);
324         }, function(xmlHttpRequest, textStatus, error) {
325                 /* ignore error. */
326         });
327 }
328
329 function unlikePost(postId) {
330         $.getJSON("unlike.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
331                 if ((data == null) || !data.success) {
332                         return;
333                 }
334                 $("#sone .post#" + postId + " > .inner-part > .status-line .unlike").addClass("hidden");
335                 $("#sone .post#" + postId + " > .inner-part > .status-line .like").removeClass("hidden");
336                 updatePostLikes(postId);
337         }, function(xmlHttpRequest, textStatus, error) {
338                 /* ignore error. */
339         });
340 }
341
342 function updatePostLikes(postId) {
343         $.getJSON("getLikes.ajax", { "type": "post", "post": postId }, function(data, textStatus) {
344                 if ((data != null) && data.success) {
345                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes").toggleClass("hidden", data.likes == 0)
346                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes span.like-count").text(data.likes);
347                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes > span").attr("title", generateSoneList(data.sones));
348                 }
349         }, function(xmlHttpRequest, textStatus, error) {
350                 /* ignore error. */
351         });
352 }
353
354 function likeReply(replyId) {
355         $.getJSON("like.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data, textStatus) {
356                 if ((data == null) || !data.success) {
357                         return;
358                 }
359                 $("#sone .reply#" + replyId + " .status-line .like").addClass("hidden");
360                 $("#sone .reply#" + replyId + " .status-line .unlike").removeClass("hidden");
361                 updateReplyLikes(replyId);
362         }, function(xmlHttpRequest, textStatus, error) {
363                 /* ignore error. */
364         });
365 }
366
367 function unlikeReply(replyId) {
368         $.getJSON("unlike.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data, textStatus) {
369                 if ((data == null) || !data.success) {
370                         return;
371                 }
372                 $("#sone .reply#" + replyId + " .status-line .unlike").addClass("hidden");
373                 $("#sone .reply#" + replyId + " .status-line .like").removeClass("hidden");
374                 updateReplyLikes(replyId);
375         }, function(xmlHttpRequest, textStatus, error) {
376                 /* ignore error. */
377         });
378 }
379
380 function updateReplyLikes(replyId) {
381         $.getJSON("getLikes.ajax", { "type": "reply", "reply": replyId }, function(data, textStatus) {
382                 if ((data != null) && data.success) {
383                         $("#sone .reply#" + replyId + " .status-line .likes").toggleClass("hidden", data.likes == 0)
384                         $("#sone .reply#" + replyId + " .status-line .likes span.like-count").text(data.likes);
385                         $("#sone .reply#" + replyId + " .status-line .likes > span").attr("title", generateSoneList(data.sones));
386                 }
387         }, function(xmlHttpRequest, textStatus, error) {
388                 /* ignore error. */
389         });
390 }
391
392 /**
393  * Posts a reply and calls the given callback when the request finishes.
394  *
395  * @param postId
396  *            The ID of the post the reply refers to
397  * @param text
398  *            The text to post
399  * @param callbackFunction
400  *            The callback function to call when the request finishes (takes 3
401  *            parameters: success, error, replyId)
402  */
403 function postReply(postId, text, callbackFunction) {
404         $.getJSON("createReply.ajax", { "formPassword" : getFormPassword(), "post" : postId, "text": text }, function(data, textStatus) {
405                 if (data == null) {
406                         /* TODO - show error */
407                         return;
408                 }
409                 if (data.success) {
410                         callbackFunction(true, null, data.reply);
411                 } else {
412                         callbackFunction(false, data.error);
413                 }
414         }, function(xmlHttpRequest, textStatus, error) {
415                 /* ignore error. */
416         });
417 }
418
419 /**
420  * Requests information about the reply with the given ID.
421  *
422  * @param replyId
423  *            The ID of the reply
424  * @param callbackFunction
425  *            A callback function (parameters soneId, soneName, replyTime,
426  *            replyDisplayTime, text, html)
427  */
428 function getReply(replyId, callbackFunction) {
429         $.getJSON("getReply.ajax", { "reply" : replyId }, function(data, textStatus) {
430                 if ((data != null) && data.success) {
431                         callbackFunction(data.soneId, data.soneName, data.time, data.displayTime, data.text, data.html);
432                 }
433         }, function(xmlHttpRequest, textStatus, error) {
434                 /* ignore error. */
435         });
436 }
437
438 /**
439  * Ajaxifies the given post by enhancing all eligible elements with AJAX.
440  *
441  * @param postElement
442  *            The post element to ajaxify
443  */
444 function ajaxifyPost(postElement) {
445         $(postElement).find("form").submit(function() {
446                 return false;
447         });
448         $(postElement).find(".create-reply button:submit").click(function() {
449                 inputField = $(this.form).find(":input:enabled").get(0);
450                 postId = getPostId(this);
451                 text = $(inputField).val();
452                 $(inputField).val("");
453                 postReply(postId, text, function(success, error, replyId) {
454                         if (success) {
455                                 loadNewReply(replyId);
456                                 markPostAsKnown(getPostElement(inputField));
457                                 $("#sone .post#" + postId + " .create-reply").addClass("hidden");
458                         } else {
459                                 alert(error);
460                         }
461                 });
462                 return false;
463         });
464
465         /* replace all “delete” buttons with javascript. */
466         (function(postElement) {
467                 getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
468                         postId = getPostId(postElement);
469                         enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
470                 });
471         })(postElement);
472
473         /* convert all “like” buttons to javascript functions. */
474         $(postElement).find(".like-post").submit(function() {
475                 likePost(getPostId(this));
476                 markPostAsKnown(getPostElement(this));
477                 return false;
478         });
479         $(postElement).find(".unlike-post").submit(function() {
480                 unlikePost(getPostId(this));
481                 markPostAsKnown(getPostElement(this));
482                 return false;
483         });
484
485         /* add “comment” link. */
486         addCommentLink(getPostId(postElement), postElement, $(postElement).find(".post-status-line .time"));
487
488         /* process all replies. */
489         $(postElement).find(".reply").each(function() {
490                 ajaxifyReply(this);
491         });
492
493         /* process reply input fields. */
494         getTranslation("WebInterface.DefaultText.Reply", function(text) {
495                 $(postElement).find("input.reply-input").each(function() {
496                         registerInputTextareaSwap(this, text, "text", false, false);
497                 });
498         });
499
500         /* mark everything as known on click. */
501         $(postElement).click(function() {
502                 markPostAsKnown(this);
503         });
504
505         /* hide reply input field. */
506         $(postElement).find(".create-reply").addClass("hidden");
507 }
508
509 /**
510  * Ajaxifies the given reply element.
511  *
512  * @param replyElement
513  *            The reply element to ajaxify
514  */
515 function ajaxifyReply(replyElement) {
516         $(replyElement).find(".like-reply").submit(function() {
517                 likeReply(getReplyId(this));
518                 markPostAsKnown(getPostElement(this));
519                 return false;
520         });
521         $(replyElement).find(".unlike-reply").submit(function() {
522                 unlikeReply(getReplyId(this));
523                 markPostAsKnown(getPostElement(this));
524                 return false;
525         });
526         (function(replyElement) {
527                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
528                         $(replyElement).find(".delete-reply button").each(function() {
529                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
530                         });
531                 });
532         })(replyElement);
533         addCommentLink(getPostId(replyElement), replyElement, $(replyElement).find(".reply-status-line .time"));
534
535         /* mark post and all replies as known on click. */
536         $(replyElement).click(function() {
537                 markPostAsKnown(getPostElement(replyElement));
538         });
539 }
540
541 /**
542  * Ajaxifies the given notification by replacing the form with AJAX.
543  *
544  * @param notification
545  *            jQuery object representing the notification.
546  */
547 function ajaxifyNotification(notification) {
548         notification.find("form.dismiss").submit(function() {
549                 return false;
550         });
551         notification.find("form.dismiss button").click(function() {
552                 $.getJSON("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.attr("id") }, function(data, textStatus) {
553                         /* dismiss in case of error, too. */
554                         notification.slideUp();
555                 }, function(xmlHttpRequest, textStatus, error) {
556                         /* ignore error. */
557                 });
558         });
559         return notification;
560 }
561
562 function getStatus() {
563         $.getJSON("getStatus.ajax", {"loadAllSones": isKnownSonesPage()}, function(data, textStatus) {
564                 if ((data != null) && data.success) {
565                         /* process Sone information. */
566                         $.each(data.sones, function(index, value) {
567                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdated);
568                         });
569                         /* process notifications. */
570                         $.each(data.notifications, function(index, value) {
571                                 oldNotification = $("#sone #notification-area .notification#" + value.id);
572                                 notification = ajaxifyNotification(createNotification(value.id, value.text, value.dismissable)).hide();
573                                 if (oldNotification.length != 0) {
574                                         oldNotification.replaceWith(notification.show());
575                                 } else {
576                                         $("#sone #notification-area").append(notification);
577                                         notification.slideDown();
578                                 }
579                                 setActivity();
580                         });
581                         $.each(data.removedNotifications, function(index, value) {
582                                 $("#sone #notification-area .notification#" + value.id).slideUp();
583                         });
584                         /* process new posts. */
585                         $.each(data.newPosts, function(index, value) {
586                                 loadNewPost(value);
587                         });
588                         /* process new replies. */
589                         $.each(data.newReplies, function(index, value) {
590                                 loadNewReply(value);
591                         });
592                         /* do it again in 5 seconds. */
593                         setTimeout(getStatus, 5000);
594                 } else {
595                         /* data.success was false, wait 30 seconds. */
596                         setTimeout(getStatus, 30000);
597                 }
598         }, function(xmlHttpRequest, textStatus, error) {
599                 /* something really bad happend, wait a minute. */
600                 setTimeout(getStatus, 60000);
601         })
602 }
603
604 /**
605  * Returns the content of the page-id attribute.
606  *
607  * @returns The page ID
608  */
609 function getPageId() {
610         return $("#sone .page-id").text();
611 }
612
613 /**
614  * Returns whether the current page is the index page.
615  *
616  * @returns {Boolean} <code>true</code> if the current page is the index page,
617  *          <code>false</code> otherwise
618  */
619 function isIndexPage() {
620         return getPageId() == "index";
621 }
622
623 /**
624  * Returns whether the current page is a “view Sone” page.
625  *
626  * @returns {Boolean} <code>true</code> if the current page is a “view Sone”
627  *          page, <code>false</code> otherwise
628  */
629 function isViewSonePage() {
630         return getPageId() == "view-sone";
631 }
632
633 /**
634  * Returns the ID of the currently shown Sone. This will only return a sensible
635  * value if isViewSonePage() returns <code>true</code>.
636  *
637  * @returns The ID of the currently shown Sone
638  */
639 function getShownSoneId() {
640         return $("#sone .sone-id").text();
641 }
642
643 /**
644  * Returns whether the current page is a “view post” page.
645  *
646  * @returns {Boolean} <code>true</code> if the current page is a “view post”
647  *          page, <code>false</code> otherwise
648  */
649 function isViewPostPage() {
650         return getPageId() == "view-post";
651 }
652
653 /**
654  * Returns the ID of the currently shown post. This will only return a sensible
655  * value if isViewPostPage() returns <code>true</code>.
656  *
657  * @returns The ID of the currently shown post
658  */
659 function getShownPostId() {
660         return $("#sone .post-id").text();
661 }
662
663 /**
664  * Returns whether the current page is the “known Sones” page.
665  *
666  * @returns {Boolean} <code>true</code> if the current page is the “known
667  *          Sones” page, <code>false</code> otherwise
668  */
669 function isKnownSonesPage() {
670         return getPageId() == "known-sones";
671 }
672
673 var loadedPosts = {};
674 var loadedReplies = {};
675
676 function loadNewPost(postId) {
677         if (postId in loadedPosts) {
678                 return;
679         }
680         loadedPosts[postId] = true;
681         $.getJSON("getPost.ajax", { "post" : postId }, function(data, textStatus) {
682                 if ((data != null) && data.success) {
683                         if (!isIndexPage() && !(isViewSonePage() && (getShownSoneId() == data.post.sone))) {
684                                 return;
685                         }
686                         var firstOlderPost = null;
687                         $("#sone .post").each(function() {
688                                 if (getPostTime(this) < data.post.time) {
689                                         firstOlderPost = $(this);
690                                         return false;
691                                 }
692                         });
693                         newPost = $(data.post.html).addClass("hidden");
694                         if (firstOlderPost != null) {
695                                 newPost.insertBefore(firstOlderPost);
696                         } else {
697                                 $("#sone .post:last").append(newPost);
698                         }
699                         ajaxifyPost(newPost);
700                         newPost.slideDown();
701                         setActivity();
702                 }
703         });
704 }
705
706 function loadNewReply(replyId) {
707         if (replyId in loadedReplies) {
708                 return;
709         }
710         loadedReplies[replyId] = true;
711         $.getJSON("getReply.ajax", { "reply": replyId }, function(data, textStatus) {
712                 /* find post. */
713                 if ((data != null) && data.success) {
714                         $("#sone .post#" + data.reply.postId).each(function() {
715                                 var firstNewerReply = null;
716                                 $(this).find(".replies .reply").each(function() {
717                                         if (getReplyTime(this) > data.reply.time) {
718                                                 firstNewerReply = $(this);
719                                                 return false;
720                                         }
721                                 });
722                                 newReply = $(data.reply.html).addClass("hidden");
723                                 if (firstNewerReply != null) {
724                                         newReply.insertBefore(firstNewerReply);
725                                 } else {
726                                         if ($(this).find(".replies .create-reply")) {
727                                                 $(this).find(".replies .create-reply").before(newReply);
728                                         } else {
729                                                 $(this).find(".replies").append(newReply);
730                                         }
731                                 }
732                                 ajaxifyReply(newReply);
733                                 newReply.slideDown();
734                                 setActivity();
735                         });
736                 }
737         });
738 }
739
740 function markPostAsKnown(postElements) {
741         $(postElements).each(function() {
742                 postElement = this;
743                 if ($(postElement).hasClass("new")) {
744                         (function(postElement) {
745                                 $.getJSON("markPostAsKnown.ajax", {"formPassword": getFormPassword(), "post": getPostId(postElement)}, function(data, textStatus) {
746                                         $(postElement).removeClass("new");
747                                 });
748                         })(postElement);
749                 }
750         });
751         markReplyAsKnown($(postElements).find(".reply"));
752 }
753
754 function markReplyAsKnown(replyElements) {
755         $(replyElements).each(function() {
756                 replyElement = this;
757                 if ($(replyElement).hasClass("new")) {
758                         (function(replyElement) {
759                                 $.getJSON("markReplyAsKnown.ajax", {"formPassword": getFormPassword(), "reply": getReplyId(replyElement)}, function(data, textStatus) {
760                                         $(replyElement).removeClass("new");
761                                 });
762                         })(replyElement);
763                 }
764         });
765 }
766
767 function resetActivity() {
768         title = document.title;
769         if (title.indexOf('(') == 0) {
770                 document.title = title.substr(title.indexOf(' ') + 1);
771         }
772 }
773
774 function setActivity() {
775         if (!focus) {
776                 title = document.title;
777                 if (title.indexOf('(') != 0) {
778                         document.title = "(!) " + title;
779                 }
780         }
781 }
782
783 /**
784  * Creates a new notification.
785  *
786  * @param id
787  *            The ID of the notificaiton
788  * @param text
789  *            The text of the notification
790  * @param dismissable
791  *            <code>true</code> if the notification can be dismissed by the
792  *            user
793  */
794 function createNotification(id, text, dismissable) {
795         notification = $("<div></div>").addClass("notification").attr("id", id);
796         if (dismissable) {
797                 dismissForm = $("#sone #notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id")
798                 dismissForm.find("input[name=notification]").val(id);
799                 notification.append(dismissForm);
800         }
801         notification.append(text);
802         return notification;
803 }
804
805 //
806 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
807 //
808
809 var focus = true;
810
811 $(document).ready(function() {
812
813         /* this initializes the status update input field. */
814         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
815                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
816                 $("#sone #update-status").submit(function() {
817                         text = $(this).find(":input:enabled").val();
818                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "text": text }, function(data, textStatus) {
819                                 if ((data != null) && data.success) {
820                                         loadNewPost(data.postId);
821                                 }
822                         });
823                         $(this).find(":input:enabled").val("").blur();
824                         return false;
825                 });
826         });
827
828         /* ajaxify input field on “view Sone” page. */
829         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
830                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
831                 $("#sone #post-message").submit(function() {
832                         text = $(this).find(":input:enabled").val();
833                         $.getJSON("ajax/createPost.ajax", { "formPassword": getFormPassword(), "recipient": $("#sone #sone-id").text(), "text": text }, function(data, textStatus) {
834                                 if ((data != null) && data.success) {
835                                         loadNewPost(data.postId);
836                                 }
837                         });
838                         $(this).find(":input:enabled").val("").blur();
839                         return false;
840                 });
841         });
842
843         /* Ajaxifies all posts. */
844         /* calling getTranslation here will cache the necessary values. */
845         getTranslation("WebInterface.Confirmation.DeletePostButton", function(text) {
846                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(text) {
847                         getTranslation("WebInterface.DefaultText.Reply", function(text) {
848                                 $("#sone .post").each(function() {
849                                         ajaxifyPost(this);
850                                 });
851                         });
852                 });
853         });
854
855         /* hides all replies but the latest two. */
856         if (!isViewPostPage()) {
857                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
858                         $("#sone .post .replies").each(function() {
859                                 allReplies = $(this).find(".reply");
860                                 if (allReplies.length > 2) {
861                                         newHidden = false;
862                                         for (replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
863                                                 $(allReplies[replyIndex]).addClass("hidden");
864                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
865                                         }
866                                         clickToShowElement = $("<div></div>").addClass("click-to-show");
867                                         if (newHidden) {
868                                                 clickToShowElement.addClass("new");
869                                         }
870                                         (function(clickToShowElement, allReplies, text) {
871                                                 clickToShowElement.text(text);
872                                                 clickToShowElement.click(function() {
873                                                         allReplies.removeClass("hidden");
874                                                         clickToShowElement.addClass("hidden");
875                                                 });
876                                         })(clickToShowElement, allReplies, text);
877                                         $(allReplies[0]).before(clickToShowElement);
878                                 }
879                         });
880                 });
881         }
882
883         /*
884          * convert all “follow”, “unfollow”, “lock”, and “unlock” links to something
885          * nicer.
886          */
887         $("#sone .follow").submit(function() {
888                 var followElement = this;
889                 $.getJSON("followSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
890                         $(followElement).addClass("hidden");
891                         $(followElement).parent().find(".unfollow").removeClass("hidden");
892                 });
893                 return false;
894         });
895         $("#sone .unfollow").submit(function() {
896                 var unfollowElement = this;
897                 $.getJSON("unfollowSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
898                         $(unfollowElement).addClass("hidden");
899                         $(unfollowElement).parent().find(".follow").removeClass("hidden");
900                 });
901                 return false;
902         });
903         $("#sone .lock").submit(function() {
904                 var lockElement = this;
905                 $.getJSON("lockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
906                         $(lockElement).addClass("hidden");
907                         $(lockElement).parent().find(".unlock").removeClass("hidden");
908                 });
909                 return false;
910         });
911         $("#sone .unlock").submit(function() {
912                 var unlockElement = this;
913                 $.getJSON("unlockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
914                         $(unlockElement).addClass("hidden");
915                         $(unlockElement).parent().find(".lock").removeClass("hidden");
916                 });
917                 return false;
918         });
919
920         /* process all existing notifications, ajaxify dismiss buttons. */
921         $("#sone #notification-area .notification").each(function() {
922                 ajaxifyNotification($(this));
923         });
924
925         /* activate status polling. */
926         setTimeout(getStatus, 5000);
927
928         /* reset activity counter when the page has focus. */
929         $(window).focus(function() {
930                 focus = true;
931                 resetActivity();
932         }).blur(function() {
933                 focus = false;
934         })
935
936 });