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