Fix iteration over all replies.
[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                                 if (!optional && (textarea.val() == "")) {
51                                         return false;
52                                 }
53                         });
54                 })($(this), textarea);
55         });
56 }
57
58 /**
59  * Adds a “comment” link to all status lines contained in the given element.
60  *
61  * @param postId
62  *            The ID of the post
63  * @param element
64  *            The element to add a “comment” link to
65  */
66 function addCommentLink(postId, element, insertAfterThisElement) {
67         if ($(element).find(".show-reply-form").length > 0) {
68                 return;
69         }
70         commentElement = (function(postId) {
71                 separator = $("<span> · </span>").addClass("separator");
72                 var commentElement = $("<div><span>Comment</span></div>").addClass("show-reply-form").click(function() {
73                         markPostAsKnown(getPostElement(this));
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         $("#sone .sone." + filterSoneId(soneId) + " .last-update span.time").text(lastUpdated);
156         $("#sone .sone." + filterSoneId(soneId) + " .profile-link a").text(name);
157 }
158
159 /**
160  * Enhances a “delete” button so that the confirmation is done on the same page.
161  *
162  * @param button
163  *            The button element
164  * @param text
165  *            The text to show on the button
166  * @param deleteCallback
167  *            The callback that actually deletes something
168  */
169 function enhanceDeleteButton(button, text, deleteCallback) {
170         (function(button) {
171                 newButton = $("<button></button>").addClass("confirm").hide().text(text).click(function() {
172                         $(this).fadeOut("slow");
173                         deleteCallback();
174                         return false;
175                 }).insertAfter(button);
176                 (function(button, newButton) {
177                         button.click(function() {
178                                 button.fadeOut("slow", function() {
179                                         newButton.fadeIn("slow");
180                                         $(document).one("click", function() {
181                                                 if (this != newButton.get(0)) {
182                                                         newButton.fadeOut(function() {
183                                                                 button.fadeIn();
184                                                         });
185                                                 }
186                                         });
187                                 });
188                                 return false;
189                         });
190                 })(button, newButton);
191         })($(button));
192 }
193
194 /**
195  * Enhances a post’s “delete” button.
196  *
197  * @param button
198  *            The button element
199  * @param postId
200  *            The ID of the post to delete
201  * @param text
202  *            The text to replace the button with
203  */
204 function enhanceDeletePostButton(button, postId, text) {
205         enhanceDeleteButton(button, text, function() {
206                 $.getJSON("deletePost.ajax", { "post": postId, "formPassword": getFormPassword() }, function(data, textStatus) {
207                         if (data == null) {
208                                 return;
209                         }
210                         if (data.success) {
211                                 $("#sone .post#" + postId).slideUp();
212                         } else if (data.error == "invalid-post-id") {
213                                 alert("Invalid post ID given!");
214                         } else if (data.error == "auth-required") {
215                                 alert("You need to be logged in.");
216                         } else if (data.error == "not-authorized") {
217                                 alert("You are not allowed to delete this post.");
218                         }
219                 }, function(xmlHttpRequest, textStatus, error) {
220                         /* ignore error. */
221                 });
222         });
223 }
224
225 /**
226  * Enhances a reply’s “delete” button.
227  *
228  * @param button
229  *            The button element
230  * @param replyId
231  *            The ID of the reply to delete
232  * @param text
233  *            The text to replace the button with
234  */
235 function enhanceDeleteReplyButton(button, replyId, text) {
236         enhanceDeleteButton(button, text, function() {
237                 $.getJSON("deleteReply.ajax", { "reply": replyId, "formPassword": $("#sone #formPassword").text() }, function(data, textStatus) {
238                         if (data == null) {
239                                 return;
240                         }
241                         if (data.success) {
242                                 $("#sone .reply#" + replyId).slideUp();
243                         } else if (data.error == "invalid-reply-id") {
244                                 alert("Invalid reply ID given!");
245                         } else if (data.error == "auth-required") {
246                                 alert("You need to be logged in.");
247                         } else if (data.error == "not-authorized") {
248                                 alert("You are not allowed to delete this reply.");
249                         }
250                 }, function(xmlHttpRequest, textStatus, error) {
251                         /* ignore error. */
252                 });
253         });
254 }
255
256 function getFormPassword() {
257         return $("#sone #formPassword").text();
258 }
259
260 function getSoneElement(element) {
261         return $(element).closest(".sone");
262 }
263
264 /**
265  * Generates a list of Sones by concatening the names of the given sones with a
266  * new line character (“\n”).
267  *
268  * @param sones
269  *            The sones to format
270  * @returns {String} The created string
271  */
272 function generateSoneList(sones) {
273         var soneList = "";
274         $.each(sones, function() {
275                 if (soneList != "") {
276                         soneList += ", ";
277                 }
278                 soneList += this.name;
279         });
280         return soneList;
281 }
282
283 /**
284  * Returns the ID of the Sone that this element belongs to.
285  *
286  * @param element
287  *            The element to locate the matching Sone ID for
288  * @returns The ID of the Sone, or undefined
289  */
290 function getSoneId(element) {
291         return getSoneElement(element).find(".id").text();
292 }
293
294 function getPostElement(element) {
295         return $(element).closest(".post");
296 }
297
298 function getPostId(element) {
299         return getPostElement(element).attr("id");
300 }
301
302 function getPostTime(element) {
303         return getPostElement(element).find(".post-time").text();
304 }
305
306 /**
307  * Returns the author of the post the given element belongs to.
308  *
309  * @param element
310  *            The element whose post to get the author for
311  * @returns The ID of the authoring Sone
312  */
313 function getPostAuthor(element) {
314         return getPostElement(element).find(".post-author").text();
315 }
316
317 function getReplyElement(element) {
318         return $(element).closest(".reply");
319 }
320
321 function getReplyId(element) {
322         return getReplyElement(element).attr("id");
323 }
324
325 function getReplyTime(element) {
326         return getReplyElement(element).find(".reply-time").text();
327 }
328
329 /**
330  * Returns the author of the reply the given element belongs to.
331  *
332  * @param element
333  *            The element whose reply to get the author for
334  * @returns The ID of the authoring Sone
335  */
336 function getReplyAuthor(element) {
337         return getReplyElement(element).find(".reply-author").text();
338 }
339
340 function likePost(postId) {
341         $.getJSON("like.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
342                 if ((data == null) || !data.success) {
343                         return;
344                 }
345                 $("#sone .post#" + postId + " > .inner-part > .status-line .like").addClass("hidden");
346                 $("#sone .post#" + postId + " > .inner-part > .status-line .unlike").removeClass("hidden");
347                 updatePostLikes(postId);
348         }, function(xmlHttpRequest, textStatus, error) {
349                 /* ignore error. */
350         });
351 }
352
353 function unlikePost(postId) {
354         $.getJSON("unlike.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
355                 if ((data == null) || !data.success) {
356                         return;
357                 }
358                 $("#sone .post#" + postId + " > .inner-part > .status-line .unlike").addClass("hidden");
359                 $("#sone .post#" + postId + " > .inner-part > .status-line .like").removeClass("hidden");
360                 updatePostLikes(postId);
361         }, function(xmlHttpRequest, textStatus, error) {
362                 /* ignore error. */
363         });
364 }
365
366 function updatePostLikes(postId) {
367         $.getJSON("getLikes.ajax", { "type": "post", "post": postId }, function(data, textStatus) {
368                 if ((data != null) && data.success) {
369                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes").toggleClass("hidden", data.likes == 0)
370                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes span.like-count").text(data.likes);
371                         $("#sone .post#" + postId + " > .inner-part > .status-line .likes > span").attr("title", generateSoneList(data.sones));
372                 }
373         }, function(xmlHttpRequest, textStatus, error) {
374                 /* ignore error. */
375         });
376 }
377
378 function likeReply(replyId) {
379         $.getJSON("like.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data, textStatus) {
380                 if ((data == null) || !data.success) {
381                         return;
382                 }
383                 $("#sone .reply#" + replyId + " .status-line .like").addClass("hidden");
384                 $("#sone .reply#" + replyId + " .status-line .unlike").removeClass("hidden");
385                 updateReplyLikes(replyId);
386         }, function(xmlHttpRequest, textStatus, error) {
387                 /* ignore error. */
388         });
389 }
390
391 function unlikeReply(replyId) {
392         $.getJSON("unlike.ajax", { "type": "reply", "reply" : replyId, "formPassword": getFormPassword() }, function(data, textStatus) {
393                 if ((data == null) || !data.success) {
394                         return;
395                 }
396                 $("#sone .reply#" + replyId + " .status-line .unlike").addClass("hidden");
397                 $("#sone .reply#" + replyId + " .status-line .like").removeClass("hidden");
398                 updateReplyLikes(replyId);
399         }, function(xmlHttpRequest, textStatus, error) {
400                 /* ignore error. */
401         });
402 }
403
404 /**
405  * Trusts the Sone with the given ID.
406  *
407  * @param soneId
408  *            The ID of the Sone to trust
409  */
410 function trustSone(soneId) {
411         $.getJSON("trustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
412                 if ((data != null) && data.success) {
413                         updateTrustControls(soneId, data.trustValue);
414                 }
415         });
416 }
417
418 /**
419  * Distrusts the Sone with the given ID, i.e. assigns a negative trust value.
420  *
421  * @param soneId
422  *            The ID of the Sone to distrust
423  */
424 function distrustSone(soneId) {
425         $.getJSON("distrustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
426                 if ((data != null) && data.success) {
427                         updateTrustControls(soneId, data.trustValue);
428                 }
429         });
430 }
431
432 /**
433  * Untrusts the Sone with the given ID, i.e. removes any trust assignment.
434  *
435  * @param soneId
436  *            The ID of the Sone to untrust
437  */
438 function untrustSone(soneId) {
439         $.getJSON("untrustSone.ajax", { "formPassword" : getFormPassword(), "sone" : soneId }, function(data, textStatus) {
440                 if ((data != null) && data.success) {
441                         updateTrustControls(soneId, data.trustValue);
442                 }
443         });
444 }
445
446 /**
447  * Updates the trust controls for all posts and replies of the given Sone,
448  * according to the given trust value.
449  *
450  * @param soneId
451  *            The ID of the Sone to update all trust controls for
452  * @param trustValue
453  *            The trust value for the Sone
454  */
455 function updateTrustControls(soneId, trustValue) {
456         $("#sone .post").each(function() {
457                 if (getPostAuthor(this) == soneId) {
458                         getPostElement(this).find(".post-trust").toggleClass("hidden", trustValue != null);
459                         getPostElement(this).find(".post-distrust").toggleClass("hidden", (trustValue != null) && (trustValue < 0));
460                         getPostElement(this).find(".post-untrust").toggleClass("hidden", trustValue == null);
461                 }
462         });
463         $("#sone .reply").each(function() {
464                 if (getReplyAuthor(this) == soneId) {
465                         getReplyElement(this).find(".reply-trust").toggleClass("hidden", trustValue != null);
466                         getReplyElement(this).find(".reply-distrust").toggleClass("hidden", (trustValue != null) && (trustValue < 0));
467                         getReplyElement(this).find(".reply-untrust").toggleClass("hidden", trustValue == null);
468                 }
469         });
470 }
471
472 function updateReplyLikes(replyId) {
473         $.getJSON("getLikes.ajax", { "type": "reply", "reply": replyId }, function(data, textStatus) {
474                 if ((data != null) && data.success) {
475                         $("#sone .reply#" + replyId + " .status-line .likes").toggleClass("hidden", data.likes == 0)
476                         $("#sone .reply#" + replyId + " .status-line .likes span.like-count").text(data.likes);
477                         $("#sone .reply#" + replyId + " .status-line .likes > span").attr("title", generateSoneList(data.sones));
478                 }
479         }, function(xmlHttpRequest, textStatus, error) {
480                 /* ignore error. */
481         });
482 }
483
484 /**
485  * Posts a reply and calls the given callback when the request finishes.
486  *
487  * @param postId
488  *            The ID of the post the reply refers to
489  * @param text
490  *            The text to post
491  * @param callbackFunction
492  *            The callback function to call when the request finishes (takes 3
493  *            parameters: success, error, replyId)
494  */
495 function postReply(postId, text, callbackFunction) {
496         $.getJSON("createReply.ajax", { "formPassword" : getFormPassword(), "post" : postId, "text": text }, function(data, textStatus) {
497                 if (data == null) {
498                         /* TODO - show error */
499                         return;
500                 }
501                 if (data.success) {
502                         callbackFunction(true, null, data.reply);
503                 } else {
504                         callbackFunction(false, data.error);
505                 }
506         }, function(xmlHttpRequest, textStatus, error) {
507                 /* ignore error. */
508         });
509 }
510
511 /**
512  * Requests information about the reply with the given ID.
513  *
514  * @param replyId
515  *            The ID of the reply
516  * @param callbackFunction
517  *            A callback function (parameters soneId, soneName, replyTime,
518  *            replyDisplayTime, text, html)
519  */
520 function getReply(replyId, callbackFunction) {
521         $.getJSON("getReply.ajax", { "reply" : replyId }, function(data, textStatus) {
522                 if ((data != null) && data.success) {
523                         callbackFunction(data.soneId, data.soneName, data.time, data.displayTime, data.text, data.html);
524                 }
525         }, function(xmlHttpRequest, textStatus, error) {
526                 /* ignore error. */
527         });
528 }
529
530 /**
531  * Ajaxifies the given post by enhancing all eligible elements with AJAX.
532  *
533  * @param postElement
534  *            The post element to ajaxify
535  */
536 function ajaxifyPost(postElement) {
537         $(postElement).find("form").submit(function() {
538                 return false;
539         });
540         $(postElement).find(".create-reply button:submit").click(function() {
541                 inputField = $(this.form).find(":input:enabled").get(0);
542                 postId = getPostId(this);
543                 text = $(inputField).val();
544                 (function(postId, text, inputField) {
545                         postReply(postId, text, function(success, error, replyId) {
546                                 if (success) {
547                                         $(inputField).val("");
548                                         loadNewReply(replyId);
549                                         markPostAsKnown(getPostElement(inputField));
550                                         $("#sone .post#" + postId + " .create-reply").addClass("hidden");
551                                 } else {
552                                         alert(error);
553                                 }
554                         });
555                 })(postId, text, inputField);
556                 return false;
557         });
558
559         /* replace all “delete” buttons with javascript. */
560         (function(postElement) {
561                 getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
562                         postId = getPostId(postElement);
563                         enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
564                 });
565         })(postElement);
566
567         /* convert all “like” buttons to javascript functions. */
568         $(postElement).find(".like-post").submit(function() {
569                 likePost(getPostId(this));
570                 markPostAsKnown(getPostElement(this));
571                 return false;
572         });
573         $(postElement).find(".unlike-post").submit(function() {
574                 unlikePost(getPostId(this));
575                 markPostAsKnown(getPostElement(this));
576                 return false;
577         });
578
579         /* convert trust control buttons to javascript functions. */
580         $(postElement).find(".post-trust").submit(function() {
581                 trustSone(getPostAuthor(this));
582                 return false;
583         });
584         $(postElement).find(".post-distrust").submit(function() {
585                 distrustSone(getPostAuthor(this));
586                 return false;
587         });
588         $(postElement).find(".post-untrust").submit(function() {
589                 untrustSone(getPostAuthor(this));
590                 return false;
591         });
592
593         /* add “comment” link. */
594         addCommentLink(getPostId(postElement), postElement, $(postElement).find(".post-status-line .time"));
595
596         /* process all replies. */
597         $(postElement).find(".reply").each(function() {
598                 ajaxifyReply(this);
599         });
600
601         /* process reply input fields. */
602         getTranslation("WebInterface.DefaultText.Reply", function(text) {
603                 $(postElement).find("input.reply-input").each(function() {
604                         registerInputTextareaSwap(this, text, "text", false, false);
605                 });
606         });
607
608         /* mark everything as known on click. */
609         $(postElement).click(function() {
610                 markPostAsKnown(this);
611         });
612
613         /* hide reply input field. */
614         $(postElement).find(".create-reply").addClass("hidden");
615 }
616
617 /**
618  * Ajaxifies the given reply element.
619  *
620  * @param replyElement
621  *            The reply element to ajaxify
622  */
623 function ajaxifyReply(replyElement) {
624         $(replyElement).find(".like-reply").submit(function() {
625                 likeReply(getReplyId(this));
626                 markPostAsKnown(getPostElement(this));
627                 return false;
628         });
629         $(replyElement).find(".unlike-reply").submit(function() {
630                 unlikeReply(getReplyId(this));
631                 markPostAsKnown(getPostElement(this));
632                 return false;
633         });
634         (function(replyElement) {
635                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
636                         $(replyElement).find(".delete-reply button").each(function() {
637                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
638                         });
639                 });
640         })(replyElement);
641         addCommentLink(getPostId(replyElement), replyElement, $(replyElement).find(".reply-status-line .time"));
642
643         /* mark post and all replies as known on click. */
644         $(replyElement).click(function() {
645                 markPostAsKnown(getPostElement(this));
646         });
647 }
648
649 /**
650  * Ajaxifies the given notification by replacing the form with AJAX.
651  *
652  * @param notification
653  *            jQuery object representing the notification.
654  */
655 function ajaxifyNotification(notification) {
656         notification.find("form.dismiss").submit(function() {
657                 return false;
658         });
659         notification.find("form.dismiss button").click(function() {
660                 $.getJSON("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.attr("id") }, function(data, textStatus) {
661                         /* dismiss in case of error, too. */
662                         notification.slideUp();
663                 }, function(xmlHttpRequest, textStatus, error) {
664                         /* ignore error. */
665                 });
666         });
667         return notification;
668 }
669
670 function getStatus() {
671         $.getJSON("getStatus.ajax", {"loadAllSones": isKnownSonesPage()}, function(data, textStatus) {
672                 if ((data != null) && data.success) {
673                         /* process Sone information. */
674                         $.each(data.sones, function(index, value) {
675                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdated);
676                         });
677                         /* process notifications. */
678                         $.each(data.notifications, function(index, value) {
679                                 oldNotification = $("#sone #notification-area .notification#" + value.id);
680                                 notification = ajaxifyNotification(createNotification(value.id, value.text, value.dismissable)).hide();
681                                 if (oldNotification.length != 0) {
682                                         oldNotification.replaceWith(notification.show());
683                                 } else {
684                                         $("#sone #notification-area").append(notification);
685                                         notification.slideDown();
686                                 }
687                                 setActivity();
688                         });
689                         $.each(data.removedNotifications, function(index, value) {
690                                 $("#sone #notification-area .notification#" + value.id).slideUp();
691                         });
692                         /* process new posts. */
693                         $.each(data.newPosts, function(index, value) {
694                                 loadNewPost(value);
695                         });
696                         /* process new replies. */
697                         $.each(data.newReplies, function(index, value) {
698                                 loadNewReply(value);
699                         });
700                         /* do it again in 5 seconds. */
701                         setTimeout(getStatus, 5000);
702                 } else {
703                         /* data.success was false, wait 30 seconds. */
704                         setTimeout(getStatus, 30000);
705                 }
706         }, function(xmlHttpRequest, textStatus, error) {
707                 /* something really bad happend, wait a minute. */
708                 setTimeout(getStatus, 60000);
709         })
710 }
711
712 /**
713  * Returns the content of the page-id attribute.
714  *
715  * @returns The page ID
716  */
717 function getPageId() {
718         return $("#sone .page-id").text();
719 }
720
721 /**
722  * Returns whether the current page is the index page.
723  *
724  * @returns {Boolean} <code>true</code> if the current page is the index page,
725  *          <code>false</code> otherwise
726  */
727 function isIndexPage() {
728         return getPageId() == "index";
729 }
730
731 /**
732  * Returns whether the current page is a “view Sone” page.
733  *
734  * @returns {Boolean} <code>true</code> if the current page is a “view Sone”
735  *          page, <code>false</code> otherwise
736  */
737 function isViewSonePage() {
738         return getPageId() == "view-sone";
739 }
740
741 /**
742  * Returns the ID of the currently shown Sone. This will only return a sensible
743  * value if isViewSonePage() returns <code>true</code>.
744  *
745  * @returns The ID of the currently shown Sone
746  */
747 function getShownSoneId() {
748         return $("#sone .sone-id").text();
749 }
750
751 /**
752  * Returns whether the current page is a “view post” page.
753  *
754  * @returns {Boolean} <code>true</code> if the current page is a “view post”
755  *          page, <code>false</code> otherwise
756  */
757 function isViewPostPage() {
758         return getPageId() == "view-post";
759 }
760
761 /**
762  * Returns the ID of the currently shown post. This will only return a sensible
763  * value if isViewPostPage() returns <code>true</code>.
764  *
765  * @returns The ID of the currently shown post
766  */
767 function getShownPostId() {
768         return $("#sone .post-id").text();
769 }
770
771 /**
772  * Returns whether the current page is the “known Sones” page.
773  *
774  * @returns {Boolean} <code>true</code> if the current page is the “known
775  *          Sones” page, <code>false</code> otherwise
776  */
777 function isKnownSonesPage() {
778         return getPageId() == "known-sones";
779 }
780
781 /**
782  * Returns whether a post with the given ID exists on the current page.
783  *
784  * @param postId
785  *            The post ID to check for
786  * @returns {Boolean} <code>true</code> if a post with the given ID already
787  *          exists on the page, <code>false</code> otherwise
788  */
789 function hasPost(postId) {
790         return $(".post#" + postId).length > 0;
791 }
792
793 /**
794  * Returns whether a reply with the given ID exists on the current page.
795  *
796  * @param replyId
797  *            The reply ID to check for
798  * @returns {Boolean} <code>true</code> if a reply with the given ID already
799  *          exists on the page, <code>false</code> otherwise
800  */
801 function hasReply(replyId) {
802         return $("#sone .reply#" + replyId).length > 0;
803 }
804
805 function loadNewPost(postId) {
806         if (hasPost(postId)) {
807                 return;
808         }
809         $.getJSON("getPost.ajax", { "post" : postId }, function(data, textStatus) {
810                 if ((data != null) && data.success) {
811                         if (hasPost(data.post.id)) {
812                                 return;
813                         }
814                         if (!isIndexPage() && !(isViewSonePage() && ((getShownSoneId() == data.post.sone) || (getShownSoneId() == data.post.recipient)))) {
815                                 return;
816                         }
817                         var firstOlderPost = null;
818                         $("#sone .post").each(function() {
819                                 if (getPostTime(this) < data.post.time) {
820                                         firstOlderPost = $(this);
821                                         return false;
822                                 }
823                         });
824                         newPost = $(data.post.html).addClass("hidden");
825                         if (firstOlderPost != null) {
826                                 newPost.insertBefore(firstOlderPost);
827                         } else {
828                                 $("#sone #posts").append(newPost);
829                         }
830                         ajaxifyPost(newPost);
831                         newPost.slideDown();
832                         setActivity();
833                 }
834         });
835 }
836
837 function loadNewReply(replyId) {
838         if (hasReply(replyId)) {
839                 return;
840         }
841         $.getJSON("getReply.ajax", { "reply": replyId }, function(data, textStatus) {
842                 /* find post. */
843                 if ((data != null) && data.success) {
844                         if (hasReply(data.reply.id)) {
845                                 return;
846                         }
847                         $("#sone .post#" + data.reply.postId).each(function() {
848                                 var firstNewerReply = null;
849                                 $(this).find(".replies .reply").each(function() {
850                                         if (getReplyTime(this) > data.reply.time) {
851                                                 firstNewerReply = $(this);
852                                                 return false;
853                                         }
854                                 });
855                                 newReply = $(data.reply.html).addClass("hidden");
856                                 if (firstNewerReply != null) {
857                                         newReply.insertBefore(firstNewerReply);
858                                 } else {
859                                         if ($(this).find(".replies .create-reply")) {
860                                                 $(this).find(".replies .create-reply").before(newReply);
861                                         } else {
862                                                 $(this).find(".replies").append(newReply);
863                                         }
864                                 }
865                                 ajaxifyReply(newReply);
866                                 newReply.slideDown();
867                                 setActivity();
868                                 return false;
869                         });
870                 }
871         });
872 }
873
874 function markPostAsKnown(postElements) {
875         $(postElements).each(function() {
876                 postElement = this;
877                 if ($(postElement).hasClass("new")) {
878                         (function(postElement) {
879                                 $.getJSON("markPostAsKnown.ajax", {"formPassword": getFormPassword(), "post": getPostId(postElement)}, function(data, textStatus) {
880                                         $(postElement).removeClass("new");
881                                 });
882                         })(postElement);
883                 }
884         });
885         markReplyAsKnown($(postElements).find(".reply"));
886 }
887
888 function markReplyAsKnown(replyElements) {
889         $(replyElements).each(function() {
890                 replyElement = this;
891                 if ($(replyElement).hasClass("new")) {
892                         (function(replyElement) {
893                                 $.getJSON("markReplyAsKnown.ajax", {"formPassword": getFormPassword(), "reply": getReplyId(replyElement)}, function(data, textStatus) {
894                                         $(replyElement).removeClass("new");
895                                 });
896                         })(replyElement);
897                 }
898         });
899 }
900
901 function resetActivity() {
902         title = document.title;
903         if (title.indexOf('(') == 0) {
904                 document.title = title.substr(title.indexOf(' ') + 1);
905         }
906 }
907
908 function setActivity() {
909         if (!focus) {
910                 title = document.title;
911                 if (title.indexOf('(') != 0) {
912                         document.title = "(!) " + title;
913                 }
914         }
915 }
916
917 /**
918  * Creates a new notification.
919  *
920  * @param id
921  *            The ID of the notificaiton
922  * @param text
923  *            The text of the notification
924  * @param dismissable
925  *            <code>true</code> if the notification can be dismissed by the
926  *            user
927  */
928 function createNotification(id, text, dismissable) {
929         notification = $("<div></div>").addClass("notification").attr("id", id);
930         if (dismissable) {
931                 dismissForm = $("#sone #notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id")
932                 dismissForm.find("input[name=notification]").val(id);
933                 notification.append(dismissForm);
934         }
935         notification.append(text);
936         return notification;
937 }
938
939 /**
940  * Shows the details of the notification with the given ID.
941  *
942  * @param notificationId
943  *            The ID of the notification
944  */
945 function showNotificationDetails(notificationId) {
946         $("#sone .notification#" + notificationId + " .text").show();
947         $("#sone .notification#" + notificationId + " .short-text").hide();
948 }
949
950 //
951 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
952 //
953
954 var focus = true;
955
956 $(document).ready(function() {
957
958         /* this initializes the status update input field. */
959         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
960                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
961                 $("#sone #update-status").submit(function() {
962                         if ($(this).find(":input.default:enabled").length > 0) {
963                                 return false;
964                         }
965                         text = $(this).find(":input:enabled").val();
966                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "text": text }, function(data, textStatus) {
967                                 if ((data != null) && data.success) {
968                                         loadNewPost(data.postId);
969                                 }
970                         });
971                         $(this).find(":input:enabled").val("").blur();
972                         return false;
973                 });
974         });
975
976         /* ajaxify input field on “view Sone” page. */
977         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
978                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
979                 $("#sone #post-message").submit(function() {
980                         text = $(this).find(":input:enabled").val();
981                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "text": text }, function(data, textStatus) {
982                                 if ((data != null) && data.success) {
983                                         loadNewPost(data.postId);
984                                 }
985                         });
986                         $(this).find(":input:enabled").val("").blur();
987                         return false;
988                 });
989         });
990
991         /* Ajaxifies all posts. */
992         /* calling getTranslation here will cache the necessary values. */
993         getTranslation("WebInterface.Confirmation.DeletePostButton", function(text) {
994                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(text) {
995                         getTranslation("WebInterface.DefaultText.Reply", function(text) {
996                                 $("#sone .post").each(function() {
997                                         ajaxifyPost(this);
998                                 });
999                         });
1000                 });
1001         });
1002
1003         /* hides all replies but the latest two. */
1004         if (!isViewPostPage()) {
1005                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
1006                         $("#sone .post .replies").each(function() {
1007                                 allReplies = $(this).find(".reply");
1008                                 if (allReplies.length > 2) {
1009                                         newHidden = false;
1010                                         for (replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1011                                                 $(allReplies[replyIndex]).addClass("hidden");
1012                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1013                                         }
1014                                         clickToShowElement = $("<div></div>").addClass("click-to-show");
1015                                         if (newHidden) {
1016                                                 clickToShowElement.addClass("new");
1017                                         }
1018                                         (function(clickToShowElement, allReplies, text) {
1019                                                 clickToShowElement.text(text);
1020                                                 clickToShowElement.click(function() {
1021                                                         allReplies.removeClass("hidden");
1022                                                         clickToShowElement.addClass("hidden");
1023                                                 });
1024                                         })(clickToShowElement, allReplies, text);
1025                                         $(allReplies[0]).before(clickToShowElement);
1026                                 }
1027                         });
1028                 });
1029         }
1030
1031         /*
1032          * convert all “follow”, “unfollow”, “lock”, and “unlock” links to something
1033          * nicer.
1034          */
1035         $("#sone .follow").submit(function() {
1036                 var followElement = this;
1037                 $.getJSON("followSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
1038                         $(followElement).addClass("hidden");
1039                         $(followElement).parent().find(".unfollow").removeClass("hidden");
1040                 });
1041                 return false;
1042         });
1043         $("#sone .unfollow").submit(function() {
1044                 var unfollowElement = this;
1045                 $.getJSON("unfollowSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
1046                         $(unfollowElement).addClass("hidden");
1047                         $(unfollowElement).parent().find(".follow").removeClass("hidden");
1048                 });
1049                 return false;
1050         });
1051         $("#sone .lock").submit(function() {
1052                 var lockElement = this;
1053                 $.getJSON("lockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
1054                         $(lockElement).addClass("hidden");
1055                         $(lockElement).parent().find(".unlock").removeClass("hidden");
1056                 });
1057                 return false;
1058         });
1059         $("#sone .unlock").submit(function() {
1060                 var unlockElement = this;
1061                 $.getJSON("unlockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
1062                         $(unlockElement).addClass("hidden");
1063                         $(unlockElement).parent().find(".lock").removeClass("hidden");
1064                 });
1065                 return false;
1066         });
1067
1068         /* process all existing notifications, ajaxify dismiss buttons. */
1069         $("#sone #notification-area .notification").each(function() {
1070                 ajaxifyNotification($(this));
1071         });
1072
1073         /* activate status polling. */
1074         setTimeout(getStatus, 5000);
1075
1076         /* reset activity counter when the page has focus. */
1077         $(window).focus(function() {
1078                 focus = true;
1079                 resetActivity();
1080         }).blur(function() {
1081                 focus = false;
1082         })
1083
1084 });