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