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