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