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