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