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