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