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