Convert trust controls to javascript functions.
[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 }
464
465 function updateReplyLikes(replyId) {
466         $.getJSON("getLikes.ajax", { "type": "reply", "reply": replyId }, function(data, textStatus) {
467                 if ((data != null) && data.success) {
468                         $("#sone .reply#" + replyId + " .status-line .likes").toggleClass("hidden", data.likes == 0)
469                         $("#sone .reply#" + replyId + " .status-line .likes span.like-count").text(data.likes);
470                         $("#sone .reply#" + replyId + " .status-line .likes > span").attr("title", generateSoneList(data.sones));
471                 }
472         }, function(xmlHttpRequest, textStatus, error) {
473                 /* ignore error. */
474         });
475 }
476
477 /**
478  * Posts a reply and calls the given callback when the request finishes.
479  *
480  * @param postId
481  *            The ID of the post the reply refers to
482  * @param text
483  *            The text to post
484  * @param callbackFunction
485  *            The callback function to call when the request finishes (takes 3
486  *            parameters: success, error, replyId)
487  */
488 function postReply(postId, text, callbackFunction) {
489         $.getJSON("createReply.ajax", { "formPassword" : getFormPassword(), "post" : postId, "text": text }, function(data, textStatus) {
490                 if (data == null) {
491                         /* TODO - show error */
492                         return;
493                 }
494                 if (data.success) {
495                         callbackFunction(true, null, data.reply);
496                 } else {
497                         callbackFunction(false, data.error);
498                 }
499         }, function(xmlHttpRequest, textStatus, error) {
500                 /* ignore error. */
501         });
502 }
503
504 /**
505  * Requests information about the reply with the given ID.
506  *
507  * @param replyId
508  *            The ID of the reply
509  * @param callbackFunction
510  *            A callback function (parameters soneId, soneName, replyTime,
511  *            replyDisplayTime, text, html)
512  */
513 function getReply(replyId, callbackFunction) {
514         $.getJSON("getReply.ajax", { "reply" : replyId }, function(data, textStatus) {
515                 if ((data != null) && data.success) {
516                         callbackFunction(data.soneId, data.soneName, data.time, data.displayTime, data.text, data.html);
517                 }
518         }, function(xmlHttpRequest, textStatus, error) {
519                 /* ignore error. */
520         });
521 }
522
523 /**
524  * Ajaxifies the given post by enhancing all eligible elements with AJAX.
525  *
526  * @param postElement
527  *            The post element to ajaxify
528  */
529 function ajaxifyPost(postElement) {
530         $(postElement).find("form").submit(function() {
531                 return false;
532         });
533         $(postElement).find(".create-reply button:submit").click(function() {
534                 inputField = $(this.form).find(":input:enabled").get(0);
535                 postId = getPostId(this);
536                 text = $(inputField).val();
537                 (function(postId, text, inputField) {
538                         postReply(postId, text, function(success, error, replyId) {
539                                 if (success) {
540                                         $(inputField).val("");
541                                         loadNewReply(replyId);
542                                         markPostAsKnown(getPostElement(inputField));
543                                         $("#sone .post#" + postId + " .create-reply").addClass("hidden");
544                                 } else {
545                                         alert(error);
546                                 }
547                         });
548                 })(postId, text, inputField);
549                 return false;
550         });
551
552         /* replace all “delete” buttons with javascript. */
553         (function(postElement) {
554                 getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
555                         postId = getPostId(postElement);
556                         enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
557                 });
558         })(postElement);
559
560         /* convert all “like” buttons to javascript functions. */
561         $(postElement).find(".like-post").submit(function() {
562                 likePost(getPostId(this));
563                 markPostAsKnown(getPostElement(this));
564                 return false;
565         });
566         $(postElement).find(".unlike-post").submit(function() {
567                 unlikePost(getPostId(this));
568                 markPostAsKnown(getPostElement(this));
569                 return false;
570         });
571
572         /* convert trust control buttons to javascript functions. */
573         $(postElement).find(".post-trust").submit(function() {
574                 trustSone(getPostAuthor(this));
575                 return false;
576         });
577         $(postElement).find(".post-distrust").submit(function() {
578                 distrustSone(getPostAuthor(this));
579                 return false;
580         });
581         $(postElement).find(".post-untrust").submit(function() {
582                 untrustSone(getPostAuthor(this));
583                 return false;
584         });
585
586         /* add “comment” link. */
587         addCommentLink(getPostId(postElement), postElement, $(postElement).find(".post-status-line .time"));
588
589         /* process all replies. */
590         $(postElement).find(".reply").each(function() {
591                 ajaxifyReply(this);
592         });
593
594         /* process reply input fields. */
595         getTranslation("WebInterface.DefaultText.Reply", function(text) {
596                 $(postElement).find("input.reply-input").each(function() {
597                         registerInputTextareaSwap(this, text, "text", false, false);
598                 });
599         });
600
601         /* mark everything as known on click. */
602         $(postElement).click(function() {
603                 markPostAsKnown(this);
604         });
605
606         /* hide reply input field. */
607         $(postElement).find(".create-reply").addClass("hidden");
608 }
609
610 /**
611  * Ajaxifies the given reply element.
612  *
613  * @param replyElement
614  *            The reply element to ajaxify
615  */
616 function ajaxifyReply(replyElement) {
617         $(replyElement).find(".like-reply").submit(function() {
618                 likeReply(getReplyId(this));
619                 markPostAsKnown(getPostElement(this));
620                 return false;
621         });
622         $(replyElement).find(".unlike-reply").submit(function() {
623                 unlikeReply(getReplyId(this));
624                 markPostAsKnown(getPostElement(this));
625                 return false;
626         });
627         (function(replyElement) {
628                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
629                         $(replyElement).find(".delete-reply button").each(function() {
630                                 enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
631                         });
632                 });
633         })(replyElement);
634         addCommentLink(getPostId(replyElement), replyElement, $(replyElement).find(".reply-status-line .time"));
635
636         /* mark post and all replies as known on click. */
637         $(replyElement).click(function() {
638                 markPostAsKnown(getPostElement(this));
639         });
640 }
641
642 /**
643  * Ajaxifies the given notification by replacing the form with AJAX.
644  *
645  * @param notification
646  *            jQuery object representing the notification.
647  */
648 function ajaxifyNotification(notification) {
649         notification.find("form.dismiss").submit(function() {
650                 return false;
651         });
652         notification.find("form.dismiss button").click(function() {
653                 $.getJSON("dismissNotification.ajax", { "formPassword" : getFormPassword(), "notification" : notification.attr("id") }, function(data, textStatus) {
654                         /* dismiss in case of error, too. */
655                         notification.slideUp();
656                 }, function(xmlHttpRequest, textStatus, error) {
657                         /* ignore error. */
658                 });
659         });
660         return notification;
661 }
662
663 function getStatus() {
664         $.getJSON("getStatus.ajax", {"loadAllSones": isKnownSonesPage()}, function(data, textStatus) {
665                 if ((data != null) && data.success) {
666                         /* process Sone information. */
667                         $.each(data.sones, function(index, value) {
668                                 updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdated);
669                         });
670                         /* process notifications. */
671                         $.each(data.notifications, function(index, value) {
672                                 oldNotification = $("#sone #notification-area .notification#" + value.id);
673                                 notification = ajaxifyNotification(createNotification(value.id, value.text, value.dismissable)).hide();
674                                 if (oldNotification.length != 0) {
675                                         oldNotification.replaceWith(notification.show());
676                                 } else {
677                                         $("#sone #notification-area").append(notification);
678                                         notification.slideDown();
679                                 }
680                                 setActivity();
681                         });
682                         $.each(data.removedNotifications, function(index, value) {
683                                 $("#sone #notification-area .notification#" + value.id).slideUp();
684                         });
685                         /* process new posts. */
686                         $.each(data.newPosts, function(index, value) {
687                                 loadNewPost(value);
688                         });
689                         /* process new replies. */
690                         $.each(data.newReplies, function(index, value) {
691                                 loadNewReply(value);
692                         });
693                         /* do it again in 5 seconds. */
694                         setTimeout(getStatus, 5000);
695                 } else {
696                         /* data.success was false, wait 30 seconds. */
697                         setTimeout(getStatus, 30000);
698                 }
699         }, function(xmlHttpRequest, textStatus, error) {
700                 /* something really bad happend, wait a minute. */
701                 setTimeout(getStatus, 60000);
702         })
703 }
704
705 /**
706  * Returns the content of the page-id attribute.
707  *
708  * @returns The page ID
709  */
710 function getPageId() {
711         return $("#sone .page-id").text();
712 }
713
714 /**
715  * Returns whether the current page is the index page.
716  *
717  * @returns {Boolean} <code>true</code> if the current page is the index page,
718  *          <code>false</code> otherwise
719  */
720 function isIndexPage() {
721         return getPageId() == "index";
722 }
723
724 /**
725  * Returns whether the current page is a “view Sone” page.
726  *
727  * @returns {Boolean} <code>true</code> if the current page is a “view Sone”
728  *          page, <code>false</code> otherwise
729  */
730 function isViewSonePage() {
731         return getPageId() == "view-sone";
732 }
733
734 /**
735  * Returns the ID of the currently shown Sone. This will only return a sensible
736  * value if isViewSonePage() returns <code>true</code>.
737  *
738  * @returns The ID of the currently shown Sone
739  */
740 function getShownSoneId() {
741         return $("#sone .sone-id").text();
742 }
743
744 /**
745  * Returns whether the current page is a “view post” page.
746  *
747  * @returns {Boolean} <code>true</code> if the current page is a “view post”
748  *          page, <code>false</code> otherwise
749  */
750 function isViewPostPage() {
751         return getPageId() == "view-post";
752 }
753
754 /**
755  * Returns the ID of the currently shown post. This will only return a sensible
756  * value if isViewPostPage() returns <code>true</code>.
757  *
758  * @returns The ID of the currently shown post
759  */
760 function getShownPostId() {
761         return $("#sone .post-id").text();
762 }
763
764 /**
765  * Returns whether the current page is the “known Sones” page.
766  *
767  * @returns {Boolean} <code>true</code> if the current page is the “known
768  *          Sones” page, <code>false</code> otherwise
769  */
770 function isKnownSonesPage() {
771         return getPageId() == "known-sones";
772 }
773
774 /**
775  * Returns whether a post with the given ID exists on the current page.
776  *
777  * @param postId
778  *            The post ID to check for
779  * @returns {Boolean} <code>true</code> if a post with the given ID already
780  *          exists on the page, <code>false</code> otherwise
781  */
782 function hasPost(postId) {
783         return $(".post#" + postId).length > 0;
784 }
785
786 /**
787  * Returns whether a reply with the given ID exists on the current page.
788  *
789  * @param replyId
790  *            The reply ID to check for
791  * @returns {Boolean} <code>true</code> if a reply with the given ID already
792  *          exists on the page, <code>false</code> otherwise
793  */
794 function hasReply(replyId) {
795         return $("#sone .reply#" + replyId).length > 0;
796 }
797
798 function loadNewPost(postId) {
799         if (hasPost(postId)) {
800                 return;
801         }
802         $.getJSON("getPost.ajax", { "post" : postId }, function(data, textStatus) {
803                 if ((data != null) && data.success) {
804                         if (hasPost(data.post.id)) {
805                                 return;
806                         }
807                         if (!isIndexPage() && !(isViewSonePage() && ((getShownSoneId() == data.post.sone) || (getShownSoneId() == data.post.recipient)))) {
808                                 return;
809                         }
810                         var firstOlderPost = null;
811                         $("#sone .post").each(function() {
812                                 if (getPostTime(this) < data.post.time) {
813                                         firstOlderPost = $(this);
814                                         return false;
815                                 }
816                         });
817                         newPost = $(data.post.html).addClass("hidden");
818                         if (firstOlderPost != null) {
819                                 newPost.insertBefore(firstOlderPost);
820                         } else {
821                                 $("#sone #posts").append(newPost);
822                         }
823                         ajaxifyPost(newPost);
824                         newPost.slideDown();
825                         setActivity();
826                 }
827         });
828 }
829
830 function loadNewReply(replyId) {
831         if (hasReply(replyId)) {
832                 return;
833         }
834         $.getJSON("getReply.ajax", { "reply": replyId }, function(data, textStatus) {
835                 /* find post. */
836                 if ((data != null) && data.success) {
837                         if (hasReply(data.reply.id)) {
838                                 return;
839                         }
840                         $("#sone .post#" + data.reply.postId).each(function() {
841                                 var firstNewerReply = null;
842                                 $(this).find(".replies .reply").each(function() {
843                                         if (getReplyTime(this) > data.reply.time) {
844                                                 firstNewerReply = $(this);
845                                                 return false;
846                                         }
847                                 });
848                                 newReply = $(data.reply.html).addClass("hidden");
849                                 if (firstNewerReply != null) {
850                                         newReply.insertBefore(firstNewerReply);
851                                 } else {
852                                         if ($(this).find(".replies .create-reply")) {
853                                                 $(this).find(".replies .create-reply").before(newReply);
854                                         } else {
855                                                 $(this).find(".replies").append(newReply);
856                                         }
857                                 }
858                                 ajaxifyReply(newReply);
859                                 newReply.slideDown();
860                                 setActivity();
861                                 return false;
862                         });
863                 }
864         });
865 }
866
867 function markPostAsKnown(postElements) {
868         $(postElements).each(function() {
869                 postElement = this;
870                 if ($(postElement).hasClass("new")) {
871                         (function(postElement) {
872                                 $.getJSON("markPostAsKnown.ajax", {"formPassword": getFormPassword(), "post": getPostId(postElement)}, function(data, textStatus) {
873                                         $(postElement).removeClass("new");
874                                 });
875                         })(postElement);
876                 }
877         });
878         markReplyAsKnown($(postElements).find(".reply"));
879 }
880
881 function markReplyAsKnown(replyElements) {
882         $(replyElements).each(function() {
883                 replyElement = this;
884                 if ($(replyElement).hasClass("new")) {
885                         (function(replyElement) {
886                                 $.getJSON("markReplyAsKnown.ajax", {"formPassword": getFormPassword(), "reply": getReplyId(replyElement)}, function(data, textStatus) {
887                                         $(replyElement).removeClass("new");
888                                 });
889                         })(replyElement);
890                 }
891         });
892 }
893
894 function resetActivity() {
895         title = document.title;
896         if (title.indexOf('(') == 0) {
897                 document.title = title.substr(title.indexOf(' ') + 1);
898         }
899 }
900
901 function setActivity() {
902         if (!focus) {
903                 title = document.title;
904                 if (title.indexOf('(') != 0) {
905                         document.title = "(!) " + title;
906                 }
907         }
908 }
909
910 /**
911  * Creates a new notification.
912  *
913  * @param id
914  *            The ID of the notificaiton
915  * @param text
916  *            The text of the notification
917  * @param dismissable
918  *            <code>true</code> if the notification can be dismissed by the
919  *            user
920  */
921 function createNotification(id, text, dismissable) {
922         notification = $("<div></div>").addClass("notification").attr("id", id);
923         if (dismissable) {
924                 dismissForm = $("#sone #notification-area #notification-dismiss-template").clone().removeClass("hidden").removeAttr("id")
925                 dismissForm.find("input[name=notification]").val(id);
926                 notification.append(dismissForm);
927         }
928         notification.append(text);
929         return notification;
930 }
931
932 /**
933  * Shows the details of the notification with the given ID.
934  *
935  * @param notificationId
936  *            The ID of the notification
937  */
938 function showNotificationDetails(notificationId) {
939         $("#sone .notification#" + notificationId + " .text").show();
940         $("#sone .notification#" + notificationId + " .short-text").hide();
941 }
942
943 //
944 // EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
945 //
946
947 var focus = true;
948
949 $(document).ready(function() {
950
951         /* this initializes the status update input field. */
952         getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
953                 registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
954                 $("#sone #update-status").submit(function() {
955                         if ($(this).find(":input.default:enabled").length > 0) {
956                                 return false;
957                         }
958                         text = $(this).find(":input:enabled").val();
959                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "text": text }, function(data, textStatus) {
960                                 if ((data != null) && data.success) {
961                                         loadNewPost(data.postId);
962                                 }
963                         });
964                         $(this).find(":input:enabled").val("").blur();
965                         return false;
966                 });
967         });
968
969         /* ajaxify input field on “view Sone” page. */
970         getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
971                 registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
972                 $("#sone #post-message").submit(function() {
973                         text = $(this).find(":input:enabled").val();
974                         $.getJSON("createPost.ajax", { "formPassword": getFormPassword(), "recipient": getShownSoneId(), "text": text }, function(data, textStatus) {
975                                 if ((data != null) && data.success) {
976                                         loadNewPost(data.postId);
977                                 }
978                         });
979                         $(this).find(":input:enabled").val("").blur();
980                         return false;
981                 });
982         });
983
984         /* Ajaxifies all posts. */
985         /* calling getTranslation here will cache the necessary values. */
986         getTranslation("WebInterface.Confirmation.DeletePostButton", function(text) {
987                 getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(text) {
988                         getTranslation("WebInterface.DefaultText.Reply", function(text) {
989                                 $("#sone .post").each(function() {
990                                         ajaxifyPost(this);
991                                 });
992                         });
993                 });
994         });
995
996         /* hides all replies but the latest two. */
997         if (!isViewPostPage()) {
998                 getTranslation("WebInterface.ClickToShow.Replies", function(text) {
999                         $("#sone .post .replies").each(function() {
1000                                 allReplies = $(this).find(".reply");
1001                                 if (allReplies.length > 2) {
1002                                         newHidden = false;
1003                                         for (replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
1004                                                 $(allReplies[replyIndex]).addClass("hidden");
1005                                                 newHidden |= $(allReplies[replyIndex]).hasClass("new");
1006                                         }
1007                                         clickToShowElement = $("<div></div>").addClass("click-to-show");
1008                                         if (newHidden) {
1009                                                 clickToShowElement.addClass("new");
1010                                         }
1011                                         (function(clickToShowElement, allReplies, text) {
1012                                                 clickToShowElement.text(text);
1013                                                 clickToShowElement.click(function() {
1014                                                         allReplies.removeClass("hidden");
1015                                                         clickToShowElement.addClass("hidden");
1016                                                 });
1017                                         })(clickToShowElement, allReplies, text);
1018                                         $(allReplies[0]).before(clickToShowElement);
1019                                 }
1020                         });
1021                 });
1022         }
1023
1024         /*
1025          * convert all “follow”, “unfollow”, “lock”, and “unlock” links to something
1026          * nicer.
1027          */
1028         $("#sone .follow").submit(function() {
1029                 var followElement = this;
1030                 $.getJSON("followSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
1031                         $(followElement).addClass("hidden");
1032                         $(followElement).parent().find(".unfollow").removeClass("hidden");
1033                 });
1034                 return false;
1035         });
1036         $("#sone .unfollow").submit(function() {
1037                 var unfollowElement = this;
1038                 $.getJSON("unfollowSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
1039                         $(unfollowElement).addClass("hidden");
1040                         $(unfollowElement).parent().find(".follow").removeClass("hidden");
1041                 });
1042                 return false;
1043         });
1044         $("#sone .lock").submit(function() {
1045                 var lockElement = this;
1046                 $.getJSON("lockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
1047                         $(lockElement).addClass("hidden");
1048                         $(lockElement).parent().find(".unlock").removeClass("hidden");
1049                 });
1050                 return false;
1051         });
1052         $("#sone .unlock").submit(function() {
1053                 var unlockElement = this;
1054                 $.getJSON("unlockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
1055                         $(unlockElement).addClass("hidden");
1056                         $(unlockElement).parent().find(".lock").removeClass("hidden");
1057                 });
1058                 return false;
1059         });
1060
1061         /* process all existing notifications, ajaxify dismiss buttons. */
1062         $("#sone #notification-area .notification").each(function() {
1063                 ajaxifyNotification($(this));
1064         });
1065
1066         /* activate status polling. */
1067         setTimeout(getStatus, 5000);
1068
1069         /* reset activity counter when the page has focus. */
1070         $(window).focus(function() {
1071                 focus = true;
1072                 resetActivity();
1073         }).blur(function() {
1074                 focus = false;
1075         })
1076
1077 });