Merge branch 'profile-fields' into next
[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).closest(".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                 (function(postId, text, inputField) {
453                         postReply(postId, text, function(success, error, replyId) {
454                                 if (success) {
455                                         $(inputField).val("");
456                                         loadNewReply(replyId, getCurrentSoneId(), postId);
457                                         markPostAsKnown(getPostElement(inputField));
458                                         $("#sone .post#" + postId + " .create-reply").addClass("hidden");
459                                 } else {
460                                         alert(error);
461                                 }
462                         });
463                 })(postId, text, inputField);
464                 return false;
465         });
466
467         /* replace all “delete” buttons with javascript. */
468         (function(postElement) {
469                 getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
470                         postId = getPostId(postElement);
471                         enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
472                 });
473         })(postElement);
474
475         /* convert all “like” buttons to javascript functions. */
476         $(postElement).find(".like-post").submit(function() {
477                 likePost(getPostId(this));
478                 markPostAsKnown(getPostElement(this));
479                 return false;
480         });
481         $(postElement).find(".unlike-post").submit(function() {
482                 unlikePost(getPostId(this));
483                 markPostAsKnown(getPostElement(this));
484                 return false;
485         });
486
487         /* add “comment” link. */
488         addCommentLink(getPostId(postElement), postElement, $(postElement).find(".post-status-line .time"));
489
490         /* process all replies. */
491         $(postElement).find(".reply").each(function() {
492                 ajaxifyReply(this);
493         });
494
495         /* process reply input fields. */
496         getTranslation("WebInterface.DefaultText.Reply", function(text) {
497                 $(postElement).find("input.reply-input").each(function() {
498                         registerInputTextareaSwap(this, text, "text", false, false);
499                 });
500         });
501
502         /* mark everything as known on click. */
503         $(postElement).click(function(event) {
504                 if ($(event.target).hasClass("click-to-show")) {
505                         return false;
506                 }
507                 markPostAsKnown(this);
508         });
509
510         /* hide reply input field. */
511         $(postElement).find(".create-reply").addClass("hidden");
512 }
513
514 /**
515  * Ajaxifies the given reply element.
516  *
517  * @param replyElement
518  *            The reply element to ajaxify
519  */
520 function ajaxifyReply(replyElement) {
521         $(replyElement).find(".like-reply").submit(function() {
522                 likeReply(getReplyId(this));
523                 markPostAsKnown(getPostElement(this));
524                 return false;
525         });
526         $(replyElement).find(".unlike-reply").submit(function() {
527                 unlikeReply(getReplyId(this));
528                 markPostAsKnown(getPostElement(this));
529                 return false;
530         });
531         (function(replyElement) {
532                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
533                         $(replyElement).find(".delete-reply button").each(function() {
534                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
535                         });
536                 });
537         })(replyElement);
538         addCommentLink(getPostId(replyElement), replyElement, $(replyElement).find(".reply-status-line .time"));
539
540         /* mark post and all replies as known on click. */
541         $(replyElement).click(function() {
542                 markPostAsKnown(getPostElement(this));
543         });
544 }
545
546 /**
547  * Ajaxifies the given notification by replacing the form with AJAX.
548  *
549  * @param notification
550  *            jQuery object representing the notification.
551  */
552 function ajaxifyNotification(notification) {
553         notification.find("form.dismiss").submit(function() {
554                 return false;
555         });
556         notification.find("form.dismiss button").click(function() {
557                 $.getJSON("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.attr("id") }, function(data, textStatus) {
558                         /* dismiss in case of error, too. */
559                         notification.slideUp();
560                 }, function(xmlHttpRequest, textStatus, error) {
561                         /* ignore error. */
562                 });
563         });
564         return notification;
565 }
566
567 function getStatus() {
568         $.getJSON("getStatus.ajax", {"loadAllSones": isKnownSonesPage()}, function(data, textStatus) {
569                 if ((data != null) && data.success) {
570                         /* process Sone information. */
571                         $.each(data.sones, function(index, value) {
572                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdated);
573                         });
574                         /* process notifications. */
575                         $.each(data.notifications, function(index, value) {
576                                 oldNotification = $("#sone #notification-area .notification#" + value.id);
577                                 notification = ajaxifyNotification(createNotification(value.id, value.text, value.dismissable)).hide();
578                                 if (oldNotification.length != 0) {
579                                         oldNotification.replaceWith(notification.show());
580                                 } else {
581                                         $("#sone #notification-area").append(notification);
582                                         notification.slideDown();
583                                 }
584                                 setActivity();
585                         });
586                         $.each(data.removedNotifications, function(index, value) {
587                                 $("#sone #notification-area .notification#" + value.id).slideUp();
588                         });
589                         /* process new posts. */
590                         $.each(data.newPosts, function(index, value) {
591                                 loadNewPost(value.id, value.sone, value.recipient, value.time);
592                         });
593                         /* process new replies. */
594                         $.each(data.newReplies, function(index, value) {
595                                 loadNewReply(value.id, value.sone, value.post, value.postSone);
596                         });
597                         /* do it again in 5 seconds. */
598                         setTimeout(getStatus, 5000);
599                 } else {
600                         /* data.success was false, wait 30 seconds. */
601                         setTimeout(getStatus, 30000);
602                 }
603         }, function(xmlHttpRequest, textStatus, error) {
604                 /* something really bad happend, wait a minute. */
605                 setTimeout(getStatus, 60000);
606         })
607 }
608
609 /**
610  * Returns the ID of the currently logged in Sone.
611  *
612  * @return The ID of the current Sone, or an empty string if no Sone is logged
613  *         in
614  */
615 function getCurrentSoneId() {
616         return $("#currentSoneId").text();
617 }
618
619 /**
620  * Returns the content of the page-id attribute.
621  *
622  * @returns The page ID
623  */
624 function getPageId() {
625         return $("#sone .page-id").text();
626 }
627
628 /**
629  * Returns whether the current page is the index page.
630  *
631  * @returns {Boolean} <code>true</code> if the current page is the index page,
632  *          <code>false</code> otherwise
633  */
634 function isIndexPage() {
635         return getPageId() == "index";
636 }
637
638 /**
639  * Returns whether the current page is a “view Sone” page.
640  *
641  * @returns {Boolean} <code>true</code> if the current page is a “view Sone”
642  *          page, <code>false</code> otherwise
643  */
644 function isViewSonePage() {
645         return getPageId() == "view-sone";
646 }
647
648 /**
649  * Returns the ID of the currently shown Sone. This will only return a sensible
650  * value if isViewSonePage() returns <code>true</code>.
651  *
652  * @returns The ID of the currently shown Sone
653  */
654 function getShownSoneId() {
655         return $("#sone .sone-id").text();
656 }
657
658 /**
659  * Returns whether the current page is a “view post” page.
660  *
661  * @returns {Boolean} <code>true</code> if the current page is a “view post”
662  *          page, <code>false</code> otherwise
663  */
664 function isViewPostPage() {
665         return getPageId() == "view-post";
666 }
667
668 /**
669  * Returns the ID of the currently shown post. This will only return a sensible
670  * value if isViewPostPage() returns <code>true</code>.
671  *
672  * @returns The ID of the currently shown post
673  */
674 function getShownPostId() {
675         return $("#sone .post-id").text();
676 }
677
678 /**
679  * Returns whether the current page is the “known Sones” page.
680  *
681  * @returns {Boolean} <code>true</code> if the current page is the “known
682  *          Sones” page, <code>false</code> otherwise
683  */
684 function isKnownSonesPage() {
685         return getPageId() == "known-sones";
686 }
687
688 /**
689  * Returns whether a post with the given ID exists on the current page.
690  *
691  * @param postId
692  *            The post ID to check for
693  * @returns {Boolean} <code>true</code> if a post with the given ID already
694  *          exists on the page, <code>false</code> otherwise
695  */
696 function hasPost(postId) {
697         return $(".post#" + postId).length > 0;
698 }
699
700 /**
701  * Returns whether a reply with the given ID exists on the current page.
702  *
703  * @param replyId
704  *            The reply ID to check for
705  * @returns {Boolean} <code>true</code> if a reply with the given ID already
706  *          exists on the page, <code>false</code> otherwise
707  */
708 function hasReply(replyId) {
709         return $("#sone .reply#" + replyId).length > 0;
710 }
711
712 function loadNewPost(postId, soneId, recipientId, time) {
713         if (hasPost(postId)) {
714                 return;
715         }
716         if (!isIndexPage()) {
717                 if (!isViewPostPage() || (getShownPostId() != postId)) {
718                         if (!isViewSonePage() || ((getShownSoneId() != soneId) && (getShownSoneId() != recipientId))) {
719                                 return;
720                         }
721                 }
722         }
723         if (getPostTime($("#sone .post").last()) > time) {
724                 return;
725         }
726         $.getJSON("getPost.ajax", { "post" : postId }, function(data, textStatus) {
727                 if ((data != null) && data.success) {
728                         if (hasPost(data.post.id)) {
729                                 return;
730                         }
731                         if (!isIndexPage() && !(isViewSonePage() && ((getShownSoneId() == data.post.sone) || (getShownSoneId() == data.post.recipient)))) {
732                                 return;
733                         }
734                         var firstOlderPost = null;
735                         $("#sone .post").each(function() {
736                                 if (getPostTime(this) < data.post.time) {
737                                         firstOlderPost = $(this);
738                                         return false;
739                                 }
740                         });
741                         newPost = $(data.post.html).addClass("hidden");
742                         if (firstOlderPost != null) {
743                                 newPost.insertBefore(firstOlderPost);
744                         }
745                         ajaxifyPost(newPost);
746                         newPost.slideDown();
747                         setActivity();
748                 }
749         });
750 }
751
752 function loadNewReply(replyId, soneId, postId, postSoneId) {
753         if (hasReply(replyId)) {
754                 return;
755         }
756         if (!hasPost(postId)) {
757                 return;
758         }
759         $.getJSON("getReply.ajax", { "reply": replyId }, function(data, textStatus) {
760                 /* find post. */
761                 if ((data != null) && data.success) {
762                         if (hasReply(data.reply.id)) {
763                                 return;
764                         }
765                         $("#sone .post#" + data.reply.postId).each(function() {
766                                 var firstNewerReply = null;
767                                 $(this).find(".replies .reply").each(function() {
768                                         if (getReplyTime(this) > data.reply.time) {
769                                                 firstNewerReply = $(this);
770                                                 return false;
771                                         }
772                                 });
773                                 newReply = $(data.reply.html).addClass("hidden");
774                                 if (firstNewerReply != null) {
775                                         newReply.insertBefore(firstNewerReply);
776                                 } else {
777                                         if ($(this).find(".replies .create-reply")) {
778                                                 $(this).find(".replies .create-reply").before(newReply);
779                                         } else {
780                                                 $(this).find(".replies").append(newReply);
781                                         }
782                                 }
783                                 ajaxifyReply(newReply);
784                                 newReply.slideDown();
785                                 setActivity();
786                                 return false;
787                         });
788                 }
789         });
790 }
791
792 function markPostAsKnown(postElements) {
793         $(postElements).each(function() {
794                 postElement = this;
795                 if ($(postElement).hasClass("new")) {
796                         (function(postElement) {
797                                 $.getJSON("markPostAsKnown.ajax", {"formPassword": getFormPassword(), "post": getPostId(postElement)}, function(data, textStatus) {
798                                         $(postElement).removeClass("new");
799                                         $(".click-to-show", postElement).removeClass("new");
800                                 });
801                         })(postElement);
802                 }
803         });
804         markReplyAsKnown($(postElements).find(".reply"));
805 }
806
807 function markReplyAsKnown(replyElements) {
808         $(replyElements).each(function() {
809                 replyElement = this;
810                 if ($(replyElement).hasClass("new")) {
811                         (function(replyElement) {
812                                 $.getJSON("markReplyAsKnown.ajax", {"formPassword": getFormPassword(), "reply": getReplyId(replyElement)}, function(data, textStatus) {
813                                         $(replyElement).removeClass("new");
814                                 });
815                         })(replyElement);
816                 }
817         });
818 }
819
820 function resetActivity() {
821         title = document.title;
822         if (title.indexOf('(') == 0) {
823                 document.title = title.substr(title.indexOf(' ') + 1);
824         }
825 }
826
827 function setActivity() {
828         if (!focus) {
829                 title = document.title;
830                 if (title.indexOf('(') != 0) {
831                         document.title = "(!) " + title;
832                 }
833         }
834 }
835
836 /**
837  * Creates a new notification.
838  *
839  * @param id
840  *            The ID of the notificaiton
841  * @param text
842  *            The text of the notification
843  * @param dismissable
844  *            <code>true</code> if the notification can be dismissed by the
845  *            user
846  */
847 function createNotification(id, text, dismissable) {
848         notification = $("<div></div>").addClass("notification").attr("id", id);
849         if (dismissable) {
850                 dismissForm = $("#sone #notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id")
851                 dismissForm.find("input[name=notification]").val(id);
852                 notification.append(dismissForm);
853         }
854         notification.append(text);
855         return notification;
856 }
857
858 /**
859  * Shows the details of the notification with the given ID.
860  *
861  * @param notificationId
862  *            The ID of the notification
863  */
864 function showNotificationDetails(notificationId) {
865         $("#sone .notification#" + notificationId + " .text").show();
866         $("#sone .notification#" + notificationId + " .short-text").hide();
867 }
868
869 /**
870  * Deletes the field with the given ID from the profile.
871  *
872  * @param fieldId
873  *            The ID of the field to delete
874  */
875 function deleteProfileField(fieldId) {
876         $.getJSON("deleteProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId}, function(data, textStatus) {
877                 if (data && data.success) {
878                         $("#sone .profile-field#" + data.field.id).slideUp();
879                 }
880         });
881 }
882
883 /**
884  * Renames a profile field.
885  *
886  * @param fieldId
887  *            The ID of the field to rename
888  * @param newName
889  *            The new name of the field
890  * @param successFunction
891  *            Called when the renaming was successful
892  */
893 function editProfileField(fieldId, newName, successFunction) {
894         $.getJSON("editProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "name": newName}, function(data, textStatus) {
895                 if (data && data.success) {
896                         successFunction();
897                 }
898         });
899 }
900
901 /**
902  * Moves the profile field with the given ID one slot in the given direction.
903  *
904  * @param fieldId
905  *            The ID of the field to move
906  * @param direction
907  *            The direction to move in (“up” or “down”)
908  * @param successFunction
909  *            Function to call on success
910  */
911 function moveProfileField(fieldId, direction, successFunction) {
912         $.getJSON("moveProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "direction": direction}, function(data, textStatus) {
913                 if (data && data.success) {
914                         successFunction();
915                 }
916         });
917 }
918
919 /**
920  * Moves the profile field with the given ID up one slot.
921  *
922  * @param fieldId
923  *            The ID of the field to move
924  * @param successFunction
925  *            Function to call on success
926  */
927 function moveProfileFieldUp(fieldId, successFunction) {
928         moveProfileField(fieldId, "up", successFunction);
929 }
930
931 /**
932  * Moves the profile field with the given ID down one slot.
933  *
934  * @param fieldId
935  *            The ID of the field to move
936  * @param successFunction
937  *            Function to call on success
938  */
939 function moveProfileFieldDown(fieldId, successFunction) {
940         moveProfileField(fieldId, "down", successFunction);
941 }
942
943 //
944 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
945 //
946
947 var focus = true;
948
949 $(document).ready(function() {
950
951         /* this initializes the status update input field. */
952         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
953                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
954                 $("#sone #update-status").submit(function() {
955                         if ($(this).find(":input.default:enabled").length > 0) {
956                                 return false;
957                         }
958                         text = $(this).find(":input:enabled").val();
959                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "text": text }, function(data, textStatus) {
960                                 if ((data != null) && data.success) {
961                                         loadNewPost(data.postId, getCurrentSoneId());
962                                 }
963                         });
964                         $(this).find(":input:enabled").val("").blur();
965                         return false;
966                 });
967         });
968
969         /* ajaxify input field on “view Sone” page. */
970         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
971                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
972                 $("#sone #post-message").submit(function() {
973                         text = $(this).find(":input:enabled").val();
974                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "text": text }, function(data, textStatus) {
975                                 if ((data != null) && data.success) {
976                                         loadNewPost(data.postId, getCurrentSoneId());
977                                 }
978                         });
979                         $(this).find(":input:enabled").val("").blur();
980                         return false;
981                 });
982         });
983
984         /* Ajaxifies all posts. */
985         /* calling getTranslation here will cache the necessary values. */
986         getTranslation("WebInterface.Confirmation.DeletePostButton", function(text) {
987                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(text) {
988                         getTranslation("WebInterface.DefaultText.Reply", function(text) {
989                                 $("#sone .post").each(function() {
990                                         ajaxifyPost(this);
991                                 });
992                         });
993                 });
994         });
995
996         /* hides all replies but the latest two. */
997         if (!isViewPostPage()) {
998                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
999                         $("#sone .post .replies").each(function() {
1000                                 allReplies = $(this).find(".reply");
1001                                 if (allReplies.length > 2) {
1002                                         newHidden = false;
1003                                         for (replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1004                                                 $(allReplies[replyIndex]).addClass("hidden");
1005                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1006                                         }
1007                                         clickToShowElement = $("<div></div>").addClass("click-to-show");
1008                                         if (newHidden) {
1009                                                 clickToShowElement.addClass("new");
1010                                         }
1011                                         (function(clickToShowElement, allReplies, text) {
1012                                                 clickToShowElement.text(text);
1013                                                 clickToShowElement.click(function() {
1014                                                         allReplies.removeClass("hidden");
1015                                                         clickToShowElement.addClass("hidden");
1016                                                 });
1017                                         })(clickToShowElement, allReplies, text);
1018                                         $(allReplies[0]).before(clickToShowElement);
1019                                 }
1020                         });
1021                 });
1022         }
1023
1024         /*
1025          * convert all “follow”, “unfollow”, “lock”, and “unlock” links to something
1026          * nicer.
1027          */
1028         $("#sone .follow").submit(function() {
1029                 var followElement = this;
1030                 $.getJSON("followSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
1031                         $(followElement).addClass("hidden");
1032                         $(followElement).parent().find(".unfollow").removeClass("hidden");
1033                 });
1034                 return false;
1035         });
1036         $("#sone .unfollow").submit(function() {
1037                 var unfollowElement = this;
1038                 $.getJSON("unfollowSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
1039                         $(unfollowElement).addClass("hidden");
1040                         $(unfollowElement).parent().find(".follow").removeClass("hidden");
1041                 });
1042                 return false;
1043         });
1044         $("#sone .lock").submit(function() {
1045                 var lockElement = this;
1046                 $.getJSON("lockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
1047                         $(lockElement).addClass("hidden");
1048                         $(lockElement).parent().find(".unlock").removeClass("hidden");
1049                 });
1050                 return false;
1051         });
1052         $("#sone .unlock").submit(function() {
1053                 var unlockElement = this;
1054                 $.getJSON("unlockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
1055                         $(unlockElement).addClass("hidden");
1056                         $(unlockElement).parent().find(".lock").removeClass("hidden");
1057                 });
1058                 return false;
1059         });
1060
1061         /* process all existing notifications, ajaxify dismiss buttons. */
1062         $("#sone #notification-area .notification").each(function() {
1063                 ajaxifyNotification($(this));
1064         });
1065
1066         /* activate status polling. */
1067         setTimeout(getStatus, 5000);
1068
1069         /* reset activity counter when the page has focus. */
1070         $(window).focus(function() {
1071                 focus = true;
1072                 resetActivity();
1073         }).blur(function() {
1074                 focus = false;
1075         })
1076
1077 });