Convert links to posts on the current page to relative links.
[Sone.git] / src / main / resources / static / javascript / sone.js
1 /* Sone JavaScript functions. */
2
3 /* jQuery overrides. */
4 oldGetJson = jQuery.prototype.getJSON;
5 jQuery.prototype.getJSON = function(url, data, successCallback, errorCallback) {
6         if (typeof errorCallback == "undefined") {
7                 return oldGetJson(url, data, successCallback);
8         }
9         if (jQuery.isFunction(data)) {
10                 errorCallback = successCallback;
11                 successCallback = data;
12                 data = null;
13         }
14         return jQuery.ajax({
15                 data: data,
16                 error: errorCallback,
17                 success: successCallback,
18                 url: url
19         });
20 }
21
22 function isOnline() {
23         return $("#sone").hasClass("online");
24 }
25
26 function registerInputTextareaSwap(inputElement, defaultText, inputFieldName, optional, dontUseTextarea) {
27         $(inputElement).each(function() {
28                 textarea = $(dontUseTextarea ? "<input type=\"text\" name=\"" + inputFieldName + "\">" : "<textarea name=\"" + inputFieldName + "\"></textarea>").blur(function() {
29                         if ($(this).val() == "") {
30                                 $(this).hide();
31                                 inputField = $(this).data("inputField");
32                                 inputField.show().removeAttr("disabled").addClass("default");
33                                 inputField.val(defaultText);
34                         }
35                 }).hide().data("inputField", $(this)).val($(this).val());
36                 $(this).after(textarea);
37                 (function(inputField, textarea) {
38                         inputField.focus(function() {
39                                 $(this).hide().attr("disabled", "disabled");
40                                 textarea.show().focus();
41                         });
42                         if (inputField.val() == "") {
43                                 inputField.addClass("default");
44                                 inputField.val(defaultText);
45                         } else {
46                                 inputField.hide().attr("disabled", "disabled");
47                                 textarea.show();
48                         }
49                         $(inputField.get(0).form).submit(function() {
50                                 inputField.attr("disabled", "disabled");
51                                 if (!optional && (textarea.val() == "")) {
52                                         return false;
53                                 }
54                         });
55                 })($(this), textarea);
56         });
57 }
58
59 /**
60  * Adds a “comment” link to all status lines contained in the given element.
61  *
62  * @param postId
63  *            The ID of the post
64  * @param element
65  *            The element to add a “comment” link to
66  */
67 function addCommentLink(postId, element, insertAfterThisElement) {
68         if (($(element).find(".show-reply-form").length > 0) || (getPostElement(element).find(".create-reply").length == 0)) {
69                 return;
70         }
71         commentElement = (function(postId) {
72                 separator = $("<span> · </span>").addClass("separator");
73                 var commentElement = $("<div><span>Comment</span></div>").addClass("show-reply-form").click(function() {
74                         replyElement = $("#sone .post#" + postId + " .create-reply");
75                         replyElement.removeClass("hidden");
76                         replyElement.removeClass("light");
77                         (function(replyElement) {
78                                 replyElement.find("input.reply-input").blur(function() {
79                                         if ($(this).hasClass("default")) {
80                                                 replyElement.addClass("light");
81                                         }
82                                 }).focus(function() {
83                                         replyElement.removeClass("light");
84                                 });
85                         })(replyElement);
86                         replyElement.find("input.reply-input").focus();
87                 });
88                 return commentElement;
89         })(postId);
90         $(insertAfterThisElement).after(commentElement.clone(true));
91         $(insertAfterThisElement).after(separator);
92 }
93
94 var translations = {};
95
96 /**
97  * Retrieves the translation for the given key and calls the callback function.
98  * The callback function takes a single parameter, the translated string.
99  *
100  * @param key
101  *            The key of the translation string
102  * @param callback
103  *            The callback function
104  */
105 function getTranslation(key, callback) {
106         if (key in translations) {
107                 callback(translations[key]);
108                 return;
109         }
110         $.getJSON("getTranslation.ajax", {"key": key}, function(data, textStatus) {
111                 if ((data != null) && data.success) {
112                         translations[key] = data.value;
113                         callback(data.value);
114                 }
115         }, function(xmlHttpRequest, textStatus, error) {
116                 /* ignore error. */
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) {
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").text(lastUpdated);
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                 $.getJSON("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                                 alert("Invalid post ID given!");
220                         } else if (data.error == "auth-required") {
221                                 alert("You need to be logged in.");
222                         } else if (data.error == "not-authorized") {
223                                 alert("You are not allowed to delete this post.");
224                         }
225                 }, function(xmlHttpRequest, textStatus, error) {
226                         /* ignore error. */
227                 });
228         });
229 }
230
231 /**
232  * Enhances a reply’s “delete” button.
233  *
234  * @param button
235  *            The button element
236  * @param replyId
237  *            The ID of the reply to delete
238  * @param text
239  *            The text to replace the button with
240  */
241 function enhanceDeleteReplyButton(button, replyId, text) {
242         enhanceDeleteButton(button, text, function() {
243                 $.getJSON("deleteReply.ajax", { "reply": replyId, "formPassword": $("#sone #formPassword").text() }, function(data, textStatus) {
244                         if (data == null) {
245                                 return;
246                         }
247                         if (data.success) {
248                                 $("#sone .reply#" + replyId).slideUp();
249                         } else if (data.error == "invalid-reply-id") {
250                                 alert("Invalid reply ID given!");
251                         } else if (data.error == "auth-required") {
252                                 alert("You need to be logged in.");
253                         } else if (data.error == "not-authorized") {
254                                 alert("You are not allowed to delete this reply.");
255                         }
256                 }, function(xmlHttpRequest, textStatus, error) {
257                         /* ignore error. */
258                 });
259         });
260 }
261
262 function getFormPassword() {
263         return $("#sone #formPassword").text();
264 }
265
266 function getSoneElement(element) {
267         return $(element).closest(".sone");
268 }
269
270 /**
271  * Generates a list of Sones by concatening the names of the given sones with a
272  * new line character (“\n”).
273  *
274  * @param sones
275  *            The sones to format
276  * @returns {String} The created string
277  */
278 function generateSoneList(sones) {
279         var soneList = "";
280         $.each(sones, function() {
281                 if (soneList != "") {
282                         soneList += ", ";
283                 }
284                 soneList += this.name;
285         });
286         return soneList;
287 }
288
289 /**
290  * Returns the ID of the Sone that this element belongs to.
291  *
292  * @param element
293  *            The element to locate the matching Sone ID for
294  * @returns The ID of the Sone, or undefined
295  */
296 function getSoneId(element) {
297         return getSoneElement(element).find(".id").text();
298 }
299
300 function getPostElement(element) {
301         return $(element).closest(".post");
302 }
303
304 function getPostId(element) {
305         return getPostElement(element).attr("id");
306 }
307
308 function getPostTime(element) {
309         return getPostElement(element).find(".post-time").text();
310 }
311
312 /**
313  * Returns the author of the post the given element belongs to.
314  *
315  * @param element
316  *            The element whose post to get the author for
317  * @returns The ID of the authoring Sone
318  */
319 function getPostAuthor(element) {
320         return getPostElement(element).find(".post-author").text();
321 }
322
323 function getReplyElement(element) {
324         return $(element).closest(".reply");
325 }
326
327 function getReplyId(element) {
328         return getReplyElement(element).attr("id");
329 }
330
331 function getReplyTime(element) {
332         return getReplyElement(element).find(".reply-time").text();
333 }
334
335 /**
336  * Returns the author of the reply the given element belongs to.
337  *
338  * @param element
339  *            The element whose reply to get the author for
340  * @returns The ID of the authoring Sone
341  */
342 function getReplyAuthor(element) {
343         return getReplyElement(element).find(".reply-author").text();
344 }
345
346 function likePost(postId) {
347         $.getJSON("like.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
348                 if ((data == null) || !data.success) {
349                         return;
350                 }
351                 $("#sone .post#" + postId + " > .inner-part > .status-line .like").addClass("hidden");
352                 $("#sone .post#" + postId + " > .inner-part > .status-line .unlike").removeClass("hidden");
353                 updatePostLikes(postId);
354         }, function(xmlHttpRequest, textStatus, error) {
355                 /* ignore error. */
356         });
357 }
358
359 function unlikePost(postId) {
360         $.getJSON("unlike.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
361                 if ((data == null) || !data.success) {
362                         return;
363                 }
364                 $("#sone .post#" + postId + " > .inner-part > .status-line .unlike").addClass("hidden");
365                 $("#sone .post#" + postId + " > .inner-part > .status-line .like").removeClass("hidden");
366                 updatePostLikes(postId);
367         }, function(xmlHttpRequest, textStatus, error) {
368                 /* ignore error. */
369         });
370 }
371
372 function updatePostLikes(postId) {
373         $.getJSON("getLikes.ajax", { "type": "post", "post": postId }, function(data, textStatus) {
374                 if ((data != null) && data.success) {
375                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes").toggleClass("hidden", data.likes == 0)
376                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes span.like-count").text(data.likes);
377                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes > span").attr("title", generateSoneList(data.sones));
378                 }
379         }, function(xmlHttpRequest, textStatus, error) {
380                 /* ignore error. */
381         });
382 }
383
384 function likeReply(replyId) {
385         $.getJSON("like.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data, textStatus) {
386                 if ((data == null) || !data.success) {
387                         return;
388                 }
389                 $("#sone .reply#" + replyId + " .status-line .like").addClass("hidden");
390                 $("#sone .reply#" + replyId + " .status-line .unlike").removeClass("hidden");
391                 updateReplyLikes(replyId);
392         }, function(xmlHttpRequest, textStatus, error) {
393                 /* ignore error. */
394         });
395 }
396
397 function unlikeReply(replyId) {
398         $.getJSON("unlike.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data, textStatus) {
399                 if ((data == null) || !data.success) {
400                         return;
401                 }
402                 $("#sone .reply#" + replyId + " .status-line .unlike").addClass("hidden");
403                 $("#sone .reply#" + replyId + " .status-line .like").removeClass("hidden");
404                 updateReplyLikes(replyId);
405         }, function(xmlHttpRequest, textStatus, error) {
406                 /* ignore error. */
407         });
408 }
409
410 /**
411  * Trusts the Sone with the given ID.
412  *
413  * @param soneId
414  *            The ID of the Sone to trust
415  */
416 function trustSone(soneId) {
417         $.getJSON("trustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
418                 if ((data != null) && data.success) {
419                         updateTrustControls(soneId, data.trustValue);
420                 }
421         });
422 }
423
424 /**
425  * Distrusts the Sone with the given ID, i.e. assigns a negative trust value.
426  *
427  * @param soneId
428  *            The ID of the Sone to distrust
429  */
430 function distrustSone(soneId) {
431         $.getJSON("distrustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
432                 if ((data != null) && data.success) {
433                         updateTrustControls(soneId, data.trustValue);
434                 }
435         });
436 }
437
438 /**
439  * Untrusts the Sone with the given ID, i.e. removes any trust assignment.
440  *
441  * @param soneId
442  *            The ID of the Sone to untrust
443  */
444 function untrustSone(soneId) {
445         $.getJSON("untrustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
446                 if ((data != null) && data.success) {
447                         updateTrustControls(soneId, data.trustValue);
448                 }
449         });
450 }
451
452 /**
453  * Updates the trust controls for all posts and replies of the given Sone,
454  * according to the given trust value.
455  *
456  * @param soneId
457  *            The ID of the Sone to update all trust controls for
458  * @param trustValue
459  *            The trust value for the Sone
460  */
461 function updateTrustControls(soneId, trustValue) {
462         $("#sone .post").each(function() {
463                 if (getPostAuthor(this) == soneId) {
464                         getPostElement(this).find(".post-trust").toggleClass("hidden", trustValue != null);
465                         getPostElement(this).find(".post-distrust").toggleClass("hidden", trustValue != null);
466                         getPostElement(this).find(".post-untrust").toggleClass("hidden", trustValue == null);
467                 }
468         });
469         $("#sone .reply").each(function() {
470                 if (getReplyAuthor(this) == soneId) {
471                         getReplyElement(this).find(".reply-trust").toggleClass("hidden", trustValue != null);
472                         getReplyElement(this).find(".reply-distrust").toggleClass("hidden", trustValue != null);
473                         getReplyElement(this).find(".reply-untrust").toggleClass("hidden", trustValue == null);
474                 }
475         });
476 }
477
478 function updateReplyLikes(replyId) {
479         $.getJSON("getLikes.ajax", { "type": "reply", "reply": replyId }, function(data, textStatus) {
480                 if ((data != null) && data.success) {
481                         $("#sone .reply#" + replyId + " .status-line .likes").toggleClass("hidden", data.likes == 0)
482                         $("#sone .reply#" + replyId + " .status-line .likes span.like-count").text(data.likes);
483                         $("#sone .reply#" + replyId + " .status-line .likes > span").attr("title", generateSoneList(data.sones));
484                 }
485         }, function(xmlHttpRequest, textStatus, error) {
486                 /* ignore error. */
487         });
488 }
489
490 /**
491  * Posts a reply and calls the given callback when the request finishes.
492  *
493  * @param sender
494  *            The ID of the sender
495  * @param postId
496  *            The ID of the post the reply refers to
497  * @param text
498  *            The text to post
499  * @param callbackFunction
500  *            The callback function to call when the request finishes (takes 3
501  *            parameters: success, error, replyId)
502  */
503 function postReply(sender, postId, text, callbackFunction) {
504         $.getJSON("createReply.ajax", { "formPassword" : getFormPassword(), "sender": sender, "post" : postId, "text": text }, function(data, textStatus) {
505                 if (data == null) {
506                         /* TODO - show error */
507                         return;
508                 }
509                 if (data.success) {
510                         callbackFunction(true, null, data.reply, data.sone);
511                 } else {
512                         callbackFunction(false, data.error);
513                 }
514         }, function(xmlHttpRequest, textStatus, error) {
515                 /* ignore error. */
516         });
517 }
518
519 /**
520  * Requests information about the reply with the given ID.
521  *
522  * @param replyId
523  *            The ID of the reply
524  * @param callbackFunction
525  *            A callback function (parameters soneId, soneName, replyTime,
526  *            replyDisplayTime, text, html)
527  */
528 function getReply(replyId, callbackFunction) {
529         $.getJSON("getReply.ajax", { "reply" : replyId }, function(data, textStatus) {
530                 if ((data != null) && data.success) {
531                         callbackFunction(data.soneId, data.soneName, data.time, data.displayTime, data.text, data.html);
532                 }
533         }, function(xmlHttpRequest, textStatus, error) {
534                 /* ignore error. */
535         });
536 }
537
538 /**
539  * Ajaxifies the given Sone by enhancing all eligible elements with AJAX.
540  *
541  * @param soneElement
542  *            The Sone to ajaxify
543  */
544 function ajaxifySone(soneElement) {
545         /*
546          * convert all “follow”, “unfollow”, “lock”, and “unlock” links to something
547          * nicer.
548          */
549         $(".follow", soneElement).submit(function() {
550                 var followElement = this;
551                 $.getJSON("followSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
552                         $(followElement).addClass("hidden");
553                         $(followElement).parent().find(".unfollow").removeClass("hidden");
554                 });
555                 return false;
556         });
557         $(".unfollow", soneElement).submit(function() {
558                 var unfollowElement = this;
559                 $.getJSON("unfollowSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
560                         $(unfollowElement).addClass("hidden");
561                         $(unfollowElement).parent().find(".follow").removeClass("hidden");
562                 });
563                 return false;
564         });
565         $(".lock", soneElement).submit(function() {
566                 var lockElement = this;
567                 $.getJSON("lockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
568                         $(lockElement).addClass("hidden");
569                         $(lockElement).parent().find(".unlock").removeClass("hidden");
570                 });
571                 return false;
572         });
573         $(".unlock", soneElement).submit(function() {
574                 var unlockElement = this;
575                 $.getJSON("unlockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
576                         $(unlockElement).addClass("hidden");
577                         $(unlockElement).parent().find(".lock").removeClass("hidden");
578                 });
579                 return false;
580         });
581
582         /* mark Sone as known when clicking it. */
583         $(soneElement).click(function() {
584                 markSoneAsKnown(soneElement);
585         });
586 }
587
588 /**
589  * Ajaxifies the given post by enhancing all eligible elements with AJAX.
590  *
591  * @param postElement
592  *            The post element to ajaxify
593  */
594 function ajaxifyPost(postElement) {
595         $(postElement).find("form").submit(function() {
596                 return false;
597         });
598         $(postElement).find(".create-reply button:submit").click(function() {
599                 sender = $(this.form).find(":input[name=sender]").val();
600                 inputField = $(this.form).find(":input[name=text]:enabled").get(0);
601                 postId = getPostId(this);
602                 text = $(inputField).val();
603                 (function(sender, postId, text, inputField) {
604                         postReply(sender, postId, text, function(success, error, replyId, soneId) {
605                                 if (success) {
606                                         $(inputField).val("");
607                                         loadNewReply(replyId, soneId, postId);
608                                         $("#sone .post#" + postId + " .create-reply").addClass("hidden");
609                                         $("#sone .post#" + postId + " .create-reply .sender").hide();
610                                         $("#sone .post#" + postId + " .create-reply .select-sender").show();
611                                         $("#sone .post#" + postId + " .create-reply :input[name=sender]").val(getCurrentSoneId());
612                                 } else {
613                                         alert(error);
614                                 }
615                         });
616                 })(sender, postId, text, inputField);
617                 return false;
618         });
619
620         /* replace all “delete” buttons with javascript. */
621         (function(postElement) {
622                 getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
623                         postId = getPostId(postElement);
624                         enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
625                 });
626         })(postElement);
627
628         /* convert all “like” buttons to javascript functions. */
629         $(postElement).find(".like-post").submit(function() {
630                 likePost(getPostId(this));
631                 return false;
632         });
633         $(postElement).find(".unlike-post").submit(function() {
634                 unlikePost(getPostId(this));
635                 return false;
636         });
637
638         /* convert trust control buttons to javascript functions. */
639         $(postElement).find(".post-trust").submit(function() {
640                 trustSone(getPostAuthor(this));
641                 return false;
642         });
643         $(postElement).find(".post-distrust").submit(function() {
644                 distrustSone(getPostAuthor(this));
645                 return false;
646         });
647         $(postElement).find(".post-untrust").submit(function() {
648                 untrustSone(getPostAuthor(this));
649                 return false;
650         });
651
652         /* add “comment” link. */
653         addCommentLink(getPostId(postElement), postElement, $(postElement).find(".post-status-line .time"));
654
655         /* process all replies. */
656         $(postElement).find(".reply").each(function() {
657                 ajaxifyReply(this);
658         });
659
660         /* process reply input fields. */
661         getTranslation("WebInterface.DefaultText.Reply", function(text) {
662                 $(postElement).find("input.reply-input").each(function() {
663                         registerInputTextareaSwap(this, text, "text", false, false);
664                 });
665         });
666
667         /* process sender selection. */
668         $(".select-sender", postElement).css("display", "inline");
669         $(".sender", postElement).hide();
670         $(".select-sender button", postElement).click(function() {
671                 $(".sender", postElement).show();
672                 $(".select-sender", postElement).hide();
673                 return false;
674         });
675
676         /* mark everything as known on click. */
677         $(postElement).click(function(event) {
678                 if ($(event.target).hasClass("click-to-show")) {
679                         return false;
680                 }
681                 markPostAsKnown(this);
682         });
683
684         /* hide reply input field. */
685         $(postElement).find(".create-reply").addClass("hidden");
686 }
687
688 /**
689  * Ajaxifies the given reply element.
690  *
691  * @param replyElement
692  *            The reply element to ajaxify
693  */
694 function ajaxifyReply(replyElement) {
695         $(replyElement).find(".like-reply").submit(function() {
696                 likeReply(getReplyId(this));
697                 return false;
698         });
699         $(replyElement).find(".unlike-reply").submit(function() {
700                 unlikeReply(getReplyId(this));
701                 return false;
702         });
703         (function(replyElement) {
704                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
705                         $(replyElement).find(".delete-reply button").each(function() {
706                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
707                         });
708                 });
709         })(replyElement);
710         addCommentLink(getPostId(replyElement), replyElement, $(replyElement).find(".reply-status-line .time"));
711
712         /* convert trust control buttons to javascript functions. */
713         $(replyElement).find(".reply-trust").submit(function() {
714                 trustSone(getReplyAuthor(this));
715                 return false;
716         });
717         $(replyElement).find(".reply-distrust").submit(function() {
718                 distrustSone(getReplyAuthor(this));
719                 return false;
720         });
721         $(replyElement).find(".reply-untrust").submit(function() {
722                 untrustSone(getReplyAuthor(this));
723                 return false;
724         });
725 }
726
727 /**
728  * Ajaxifies the given notification by replacing the form with AJAX.
729  *
730  * @param notification
731  *            jQuery object representing the notification.
732  */
733 function ajaxifyNotification(notification) {
734         notification.find("form").submit(function() {
735                 return false;
736         });
737         notification.find("input[name=returnPage]").val($.url.attr("relative"));
738         if (notification.find(".short-text").length > 0) {
739                 notification.find(".short-text").removeClass("hidden");
740                 notification.find(".text").addClass("hidden");
741         }
742         notification.find("form.mark-as-read button").click(function() {
743                 $.getJSON("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": $(":input[name=type]", this.form).val(), "id": $(":input[name=id]", this.form).val()});
744         });
745         notification.find("a[class^='link-']").each(function() {
746                 linkElement = $(this);
747                 if (linkElement.is("[href^='viewPost']")) {
748                         id = linkElement.attr("class").substr(5);
749                         if (hasPost(id)) {
750                                 linkElement.attr("href", "#post-" + id);
751                         }
752                 }
753         });
754         notification.find("form.dismiss button").click(function() {
755                 $.getJSON("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.attr("id") }, function(data, textStatus) {
756                         /* dismiss in case of error, too. */
757                         notification.slideUp();
758                 }, function(xmlHttpRequest, textStatus, error) {
759                         /* ignore error. */
760                 });
761         });
762         return notification;
763 }
764
765 function getStatus() {
766         $.getJSON("getStatus.ajax", {"loadAllSones": isKnownSonesPage()}, function(data, textStatus) {
767                 if ((data != null) && data.success) {
768                         /* process Sone information. */
769                         $.each(data.sones, function(index, value) {
770                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdatedUnknown ? null : value.lastUpdated);
771                         });
772                         /* process notifications. */
773                         $.each(data.notifications, function(index, value) {
774                                 oldNotification = $("#sone #notification-area .notification#" + value.id);
775                                 notification = ajaxifyNotification(createNotification(value.id, value.text, value.dismissable)).hide();
776                                 if (oldNotification.length != 0) {
777                                         if ((oldNotification.find(".short-text").length > 0) && (notification.find(".short-text").length > 0)) {
778                                                 opened = oldNotification.is(":visible") && oldNotification.find(".short-text").hasClass("hidden");
779                                                 notification.find(".short-text").toggleClass("hidden", opened);
780                                                 notification.find(".text").toggleClass("hidden", !opened);
781                                         }
782                                         oldNotification.replaceWith(notification.show());
783                                 } else {
784                                         $("#sone #notification-area").append(notification);
785                                         notification.slideDown();
786                                 }
787                                 setActivity();
788                         });
789                         $.each(data.removedNotifications, function(index, value) {
790                                 $("#sone #notification-area .notification#" + value.id).slideUp();
791                         });
792                         /* process new posts. */
793                         $.each(data.newPosts, function(index, value) {
794                                 loadNewPost(value.id, value.sone, value.recipient, value.time);
795                         });
796                         /* process new replies. */
797                         $.each(data.newReplies, function(index, value) {
798                                 loadNewReply(value.id, value.sone, value.post, value.postSone);
799                         });
800                         /* do it again in 5 seconds. */
801                         setTimeout(getStatus, 5000);
802                 } else {
803                         /* data.success was false, wait 30 seconds. */
804                         setTimeout(getStatus, 30000);
805                 }
806         }, function(xmlHttpRequest, textStatus, error) {
807                 /* something really bad happend, wait a minute. */
808                 setTimeout(getStatus, 60000);
809         })
810 }
811
812 /**
813  * Returns the ID of the currently logged in Sone.
814  *
815  * @return The ID of the current Sone, or an empty string if no Sone is logged
816  *         in
817  */
818 function getCurrentSoneId() {
819         return $("#currentSoneId").text();
820 }
821
822 /**
823  * Returns the content of the page-id attribute.
824  *
825  * @returns The page ID
826  */
827 function getPageId() {
828         return $("#sone .page-id").text();
829 }
830
831 /**
832  * Returns whether the current page is the index page.
833  *
834  * @returns {Boolean} <code>true</code> if the current page is the index page,
835  *          <code>false</code> otherwise
836  */
837 function isIndexPage() {
838         return getPageId() == "index";
839 }
840
841 /**
842  * Returns whether the current page is a “view Sone” page.
843  *
844  * @returns {Boolean} <code>true</code> if the current page is a “view Sone”
845  *          page, <code>false</code> otherwise
846  */
847 function isViewSonePage() {
848         return getPageId() == "view-sone";
849 }
850
851 /**
852  * Returns the ID of the currently shown Sone. This will only return a sensible
853  * value if isViewSonePage() returns <code>true</code>.
854  *
855  * @returns The ID of the currently shown Sone
856  */
857 function getShownSoneId() {
858         return $("#sone .sone-id").text();
859 }
860
861 /**
862  * Returns whether the current page is a “view post” page.
863  *
864  * @returns {Boolean} <code>true</code> if the current page is a “view post”
865  *          page, <code>false</code> otherwise
866  */
867 function isViewPostPage() {
868         return getPageId() == "view-post";
869 }
870
871 /**
872  * Returns the ID of the currently shown post. This will only return a sensible
873  * value if isViewPostPage() returns <code>true</code>.
874  *
875  * @returns The ID of the currently shown post
876  */
877 function getShownPostId() {
878         return $("#sone .post-id").text();
879 }
880
881 /**
882  * Returns whether the current page is the “known Sones” page.
883  *
884  * @returns {Boolean} <code>true</code> if the current page is the “known
885  *          Sones” page, <code>false</code> otherwise
886  */
887 function isKnownSonesPage() {
888         return getPageId() == "known-sones";
889 }
890
891 /**
892  * Returns whether a post with the given ID exists on the current page.
893  *
894  * @param postId
895  *            The post ID to check for
896  * @returns {Boolean} <code>true</code> if a post with the given ID already
897  *          exists on the page, <code>false</code> otherwise
898  */
899 function hasPost(postId) {
900         return $(".post#" + postId).length > 0;
901 }
902
903 /**
904  * Returns whether a reply with the given ID exists on the current page.
905  *
906  * @param replyId
907  *            The reply ID to check for
908  * @returns {Boolean} <code>true</code> if a reply with the given ID already
909  *          exists on the page, <code>false</code> otherwise
910  */
911 function hasReply(replyId) {
912         return $("#sone .reply#" + replyId).length > 0;
913 }
914
915 function loadNewPost(postId, soneId, recipientId, time) {
916         if (hasPost(postId)) {
917                 return;
918         }
919         if (!isIndexPage()) {
920                 if (!isViewPostPage() || (getShownPostId() != postId)) {
921                         if (!isViewSonePage() || ((getShownSoneId() != soneId) && (getShownSoneId() != recipientId))) {
922                                 return;
923                         }
924                 }
925         }
926         if (getPostTime($("#sone .post").last()) > time) {
927                 return;
928         }
929         $.getJSON("getPost.ajax", { "post" : postId }, function(data, textStatus) {
930                 if ((data != null) && data.success) {
931                         if (hasPost(data.post.id)) {
932                                 return;
933                         }
934                         if (!isIndexPage() && !(isViewSonePage() && ((getShownSoneId() == data.post.sone) || (getShownSoneId() == data.post.recipient)))) {
935                                 return;
936                         }
937                         var firstOlderPost = null;
938                         $("#sone .post").each(function() {
939                                 if (getPostTime(this) < data.post.time) {
940                                         firstOlderPost = $(this);
941                                         return false;
942                                 }
943                         });
944                         newPost = $(data.post.html).addClass("hidden");
945                         if (firstOlderPost != null) {
946                                 newPost.insertBefore(firstOlderPost);
947                         }
948                         ajaxifyPost(newPost);
949                         newPost.slideDown();
950                         setActivity();
951                 }
952         });
953 }
954
955 function loadNewReply(replyId, soneId, postId, postSoneId) {
956         if (hasReply(replyId)) {
957                 return;
958         }
959         if (!hasPost(postId)) {
960                 return;
961         }
962         $.getJSON("getReply.ajax", { "reply": replyId }, function(data, textStatus) {
963                 /* find post. */
964                 if ((data != null) && data.success) {
965                         if (hasReply(data.reply.id)) {
966                                 return;
967                         }
968                         $("#sone .post#" + data.reply.postId).each(function() {
969                                 var firstNewerReply = null;
970                                 $(this).find(".replies .reply").each(function() {
971                                         if (getReplyTime(this) > data.reply.time) {
972                                                 firstNewerReply = $(this);
973                                                 return false;
974                                         }
975                                 });
976                                 newReply = $(data.reply.html).addClass("hidden");
977                                 if (firstNewerReply != null) {
978                                         newReply.insertBefore(firstNewerReply);
979                                 } else {
980                                         if ($(this).find(".replies .create-reply")) {
981                                                 $(this).find(".replies .create-reply").before(newReply);
982                                         } else {
983                                                 $(this).find(".replies").append(newReply);
984                                         }
985                                 }
986                                 ajaxifyReply(newReply);
987                                 newReply.slideDown();
988                                 setActivity();
989                                 return false;
990                         });
991                 }
992         });
993 }
994
995 /**
996  * Marks the given Sone as known if it is still new.
997  *
998  * @param soneElement
999  *            The Sone to mark as known
1000  */
1001 function markSoneAsKnown(soneElement) {
1002         if ($(".new", soneElement).length > 0) {
1003                 $.getJSON("maskAsKnown.ajax", {"formPassword": getFormPassword(), "type": "sone", "id": getSoneId(soneElement)}, function(data, textStatus) {
1004                         $(soneElement).removeClass("new");
1005                 });
1006         }
1007 }
1008
1009 function markPostAsKnown(postElements) {
1010         $(postElements).each(function() {
1011                 postElement = this;
1012                 if ($(postElement).hasClass("new")) {
1013                         (function(postElement) {
1014                                 $(postElement).removeClass("new");
1015                                 $(".click-to-show", postElement).removeClass("new");
1016                                 $.getJSON("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "post", "id": getPostId(postElement)});
1017                         })(postElement);
1018                 }
1019         });
1020         markReplyAsKnown($(postElements).find(".reply"));
1021 }
1022
1023 function markReplyAsKnown(replyElements) {
1024         $(replyElements).each(function() {
1025                 replyElement = this;
1026                 if ($(replyElement).hasClass("new")) {
1027                         (function(replyElement) {
1028                                 $(replyElement).removeClass("new");
1029                                 $.getJSON("markAsKnown.ajax", {"formPassword": getFormPassword(), "type": "reply", "id": getReplyId(replyElement)});
1030                         })(replyElement);
1031                 }
1032         });
1033 }
1034
1035 function resetActivity() {
1036         title = document.title;
1037         if (title.indexOf('(') == 0) {
1038                 document.title = title.substr(title.indexOf(' ') + 1);
1039         }
1040 }
1041
1042 function setActivity() {
1043         if (!focus) {
1044                 title = document.title;
1045                 if (title.indexOf('(') != 0) {
1046                         document.title = "(!) " + title;
1047                 }
1048                 if (!iconBlinking) {
1049                         setTimeout(toggleIcon, 1500);
1050                         iconBlinking = true;
1051                 }
1052         }
1053 }
1054
1055 /** Whether the icon is currently showing activity. */
1056 var iconActive = false;
1057
1058 /** Whether the icon is currently supposed to blink. */
1059 var iconBlinking = false;
1060
1061 /**
1062  * Toggles the icon. If the window has gained focus and the icon is still
1063  * showing the activity state, it is returned to normal.
1064  */
1065 function toggleIcon() {
1066         if (focus) {
1067                 if (iconActive) {
1068                         changeIcon("images/icon.png");
1069                         iconActive = false;
1070                 }
1071                 iconBlinking = false;
1072         } else {
1073                 iconActive = !iconActive;
1074                 console.log("showing icon: " + iconActive);
1075                 changeIcon(iconActive ? "images/icon-activity.png" : "images/icon.png");
1076                 setTimeout(toggleIcon, 1500);
1077         }
1078 }
1079
1080 /**
1081  * Changes the icon of the page.
1082  *
1083  * @param iconUrl
1084  *            The new URL of the icon
1085  */
1086 function changeIcon(iconUrl) {
1087         $("link[rel=icon]").remove();
1088         $("head").append($("<link>").attr("rel", "icon").attr("type", "image/png").attr("href", iconUrl));
1089         $("iframe[id=icon-update]")[0].src += "";
1090 }
1091
1092 /**
1093  * Creates a new notification.
1094  *
1095  * @param id
1096  *            The ID of the notificaiton
1097  * @param text
1098  *            The text of the notification
1099  * @param dismissable
1100  *            <code>true</code> if the notification can be dismissed by the
1101  *            user
1102  */
1103 function createNotification(id, text, dismissable) {
1104         notification = $("<div></div>").addClass("notification").attr("id", id);
1105         if (dismissable) {
1106                 dismissForm = $("#sone #notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id")
1107                 dismissForm.find("input[name=notification]").val(id);
1108                 notification.append(dismissForm);
1109         }
1110         notification.append(text);
1111         return notification;
1112 }
1113
1114 /**
1115  * Shows the details of the notification with the given ID.
1116  *
1117  * @param notificationId
1118  *            The ID of the notification
1119  */
1120 function showNotificationDetails(notificationId) {
1121         $("#sone .notification#" + notificationId + " .text").removeClass("hidden");
1122         $("#sone .notification#" + notificationId + " .short-text").addClass("hidden");
1123 }
1124
1125 /**
1126  * Deletes the field with the given ID from the profile.
1127  *
1128  * @param fieldId
1129  *            The ID of the field to delete
1130  */
1131 function deleteProfileField(fieldId) {
1132         $.getJSON("deleteProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId}, function(data, textStatus) {
1133                 if (data && data.success) {
1134                         $("#sone .profile-field#" + data.field.id).slideUp();
1135                 }
1136         });
1137 }
1138
1139 /**
1140  * Renames a profile field.
1141  *
1142  * @param fieldId
1143  *            The ID of the field to rename
1144  * @param newName
1145  *            The new name of the field
1146  * @param successFunction
1147  *            Called when the renaming was successful
1148  */
1149 function editProfileField(fieldId, newName, successFunction) {
1150         $.getJSON("editProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "name": newName}, function(data, textStatus) {
1151                 if (data && data.success) {
1152                         successFunction();
1153                 }
1154         });
1155 }
1156
1157 /**
1158  * Moves the profile field with the given ID one slot in the given direction.
1159  *
1160  * @param fieldId
1161  *            The ID of the field to move
1162  * @param direction
1163  *            The direction to move in (“up” or “down”)
1164  * @param successFunction
1165  *            Function to call on success
1166  */
1167 function moveProfileField(fieldId, direction, successFunction) {
1168         $.getJSON("moveProfileField.ajax", {"formPassword": getFormPassword(), "field": fieldId, "direction": direction}, function(data, textStatus) {
1169                 if (data && data.success) {
1170                         successFunction();
1171                 }
1172         });
1173 }
1174
1175 /**
1176  * Moves the profile field with the given ID up one slot.
1177  *
1178  * @param fieldId
1179  *            The ID of the field to move
1180  * @param successFunction
1181  *            Function to call on success
1182  */
1183 function moveProfileFieldUp(fieldId, successFunction) {
1184         moveProfileField(fieldId, "up", successFunction);
1185 }
1186
1187 /**
1188  * Moves the profile field with the given ID down one slot.
1189  *
1190  * @param fieldId
1191  *            The ID of the field to move
1192  * @param successFunction
1193  *            Function to call on success
1194  */
1195 function moveProfileFieldDown(fieldId, successFunction) {
1196         moveProfileField(fieldId, "down", successFunction);
1197 }
1198
1199 //
1200 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
1201 //
1202
1203 var focus = true;
1204
1205 $(document).ready(function() {
1206
1207         /* this initializes the status update input field. */
1208         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
1209                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
1210                 $("#sone #update-status .select-sender").css("display", "inline");
1211                 $("#sone #update-status .sender").hide();
1212                 $("#sone #update-status .select-sender button").click(function() {
1213                         $("#sone #update-status .sender").show();
1214                         $("#sone #update-status .select-sender").hide();
1215                         return false;
1216                 });
1217                 $("#sone #update-status").submit(function() {
1218                         if ($(this).find(":input.default:enabled").length > 0) {
1219                                 return false;
1220                         }
1221                         sender = $(this).find(":input[name=sender]").val();
1222                         text = $(this).find(":input[name=text]:enabled").val();
1223                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "sender": sender, "text": text }, function(data, textStatus) {
1224                                 if ((data != null) && data.success) {
1225                                         loadNewPost(data.postId, data.sone, data.recipient);
1226                                 }
1227                         });
1228                         $(this).find(":input[name=sender]").val(getCurrentSoneId());
1229                         $(this).find(":input[name=text]:enabled").val("").blur();
1230                         $(this).find(".sender").hide();
1231                         $(this).find(".select-sender").show();
1232                         return false;
1233                 });
1234         });
1235
1236         /* ajaxify input field on “view Sone” page. */
1237         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
1238                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
1239                 $("#sone #post-message").submit(function() {
1240                         text = $(this).find(":input:enabled").val();
1241                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "text": text }, function(data, textStatus) {
1242                                 if ((data != null) && data.success) {
1243                                         loadNewPost(data.postId, getCurrentSoneId());
1244                                 }
1245                         });
1246                         $(this).find(":input:enabled").val("").blur();
1247                         return false;
1248                 });
1249         });
1250
1251         /* Ajaxifies all posts. */
1252         /* calling getTranslation here will cache the necessary values. */
1253         getTranslation("WebInterface.Confirmation.DeletePostButton", function(text) {
1254                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(text) {
1255                         getTranslation("WebInterface.DefaultText.Reply", function(text) {
1256                                 $("#sone .post").each(function() {
1257                                         ajaxifyPost(this);
1258                                 });
1259                         });
1260                 });
1261         });
1262
1263         /* hides all replies but the latest two. */
1264         if (!isViewPostPage()) {
1265                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
1266                         $("#sone .post .replies").each(function() {
1267                                 allReplies = $(this).find(".reply");
1268                                 if (allReplies.length > 2) {
1269                                         newHidden = false;
1270                                         for (replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1271                                                 $(allReplies[replyIndex]).addClass("hidden");
1272                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1273                                         }
1274                                         clickToShowElement = $("<div></div>").addClass("click-to-show");
1275                                         if (newHidden) {
1276                                                 clickToShowElement.addClass("new");
1277                                         }
1278                                         (function(clickToShowElement, allReplies, text) {
1279                                                 clickToShowElement.text(text);
1280                                                 clickToShowElement.click(function() {
1281                                                         allReplies.removeClass("hidden");
1282                                                         clickToShowElement.addClass("hidden");
1283                                                 });
1284                                         })(clickToShowElement, allReplies, text);
1285                                         $(allReplies[0]).before(clickToShowElement);
1286                                 }
1287                         });
1288                 });
1289         }
1290
1291         $("#sone .sone").each(function() {
1292                 ajaxifySone($(this));
1293         });
1294
1295         /* process all existing notifications, ajaxify dismiss buttons. */
1296         $("#sone #notification-area .notification").each(function() {
1297                 ajaxifyNotification($(this));
1298         });
1299
1300         /* activate status polling. */
1301         setTimeout(getStatus, 5000);
1302
1303         /* reset activity counter when the page has focus. */
1304         $(window).focus(function() {
1305                 focus = true;
1306                 resetActivity();
1307         }).blur(function() {
1308                 focus = false;
1309         })
1310
1311 });