Merge commit '0.3.1-RC3' into message-recipient
[Sone.git] / src / main / resources / static / javascript / sone.js
index e4527af..75facb3 100644 (file)
@@ -23,8 +23,8 @@ function isOnline() {
        return $("#sone").hasClass("online");
 }
 
-function registerInputTextareaSwap(inputSelector, defaultText, inputFieldName, optional, dontUseTextarea) {
-       $(inputSelector).each(function() {
+function registerInputTextareaSwap(inputElement, defaultText, inputFieldName, optional, dontUseTextarea) {
+       $(inputElement).each(function() {
                textarea = $(dontUseTextarea ? "<input type=\"text\" name=\"" + inputFieldName + "\">" : "<textarea name=\"" + inputFieldName + "\"></textarea>").blur(function() {
                        if ($(this).val() == "") {
                                $(this).hide();
@@ -55,17 +55,6 @@ function registerInputTextareaSwap(inputSelector, defaultText, inputFieldName, o
        });
 }
 
-/* hide all the “create reply” forms until a link is clicked. */
-function addCommentLinks() {
-       if (!isOnline()) {
-               return;
-       }
-       $("#sone .post").each(function() {
-               postId = $(this).attr("id");
-               addCommentLink(postId, $(this));
-       });
-}
-
 /**
  * Adds a “comment” link to all status lines contained in the given element.
  *
@@ -74,9 +63,13 @@ function addCommentLinks() {
  * @param element
  *            The element to add a “comment” link to
  */
-function addCommentLink(postId, element) {
+function addCommentLink(postId, element, insertAfterThisElement) {
+       if ($(element).find(".show-reply-form").length > 0) {
+               return;
+       }
        commentElement = (function(postId) {
                var commentElement = $("<div><span>Comment</span></div>").addClass("show-reply-form").click(function() {
+                       markPostAsKnown(getPostElement(this));
                        replyElement = $("#sone .post#" + postId + " .create-reply");
                        replyElement.removeClass("hidden");
                        replyElement.removeClass("light");
@@ -93,12 +86,11 @@ function addCommentLink(postId, element) {
                });
                return commentElement;
        })(postId);
-       element.find(".create-reply").addClass("hidden");
-       element.find(".status-line .time").each(function() {
-               $(this).after(commentElement.clone(true));
-       });
+       $(insertAfterThisElement).after(commentElement.clone(true));
 }
 
+var translations = {};
+
 /**
  * Retrieves the translation for the given key and calls the callback function.
  * The callback function takes a single parameter, the translated string.
@@ -109,8 +101,13 @@ function addCommentLink(postId, element) {
  *            The callback function
  */
 function getTranslation(key, callback) {
+       if (key in translations) {
+               callback(translations[key]);
+               return;
+       }
        $.getJSON("ajax/getTranslation.ajax", {"key": key}, function(data, textStatus) {
                if ((data != null) && data.success) {
+                       translations[key] = data.value;
                        callback(data.value);
                }
        }, function(xmlHttpRequest, textStatus, error) {
@@ -119,33 +116,6 @@ function getTranslation(key, callback) {
 }
 
 /**
- * Fires off an AJAX request to retrieve the current status of a Sone.
- *
- * @param soneId
- *            The ID of the Sone
- * @param local
- *            <code>true</code> if the Sone is local, <code>false</code>
- *            otherwise
- */
-function getSoneStatus(soneId, local) {
-       $.getJSON("ajax/getSoneStatus.ajax", {"sone": soneId}, function(data, textStatus) {
-               if ((data != null) && data.success) {
-                       updateSoneStatus(soneId, data.name, data.status, data.modified, data.locked, data.lastUpdated);
-               }
-               /* seconds! */
-               updateInterval = 60;
-               if (local || (data!= null) && (data.modified || (data.status == "downloading") || (data.status == "inserting"))) {
-                       updateInterval = 5;
-               }
-               setTimeout(function() {
-                       getSoneStatus(soneId, local);
-               }, updateInterval * 1000);
-       }, function(xmlHttpRequest, textStatus, error) {
-               /* ignore error. */
-       });
-}
-
-/**
  * Filters the given Sone ID, replacing all “~” characters by an underscore.
  *
  * @param soneId
@@ -184,41 +154,17 @@ function updateSoneStatus(soneId, name, status, modified, locked, lastUpdated) {
        $("#sone .sone." + filterSoneId(soneId) + " .profile-link a").text(name);
 }
 
-var watchedSones = {};
-
-/**
- * Watches this Sone for updates to its status.
- *
- * @param soneId
- *            The ID of the Sone to watch
- * @param local
- *            <code>true</code> if the Sone is local, <code>false</code>
- *            otherwise
- */
-function watchSone(soneId, local) {
-       if (watchedSones[soneId]) {
-               return;
-       }
-       watchedSones[soneId] = true;
-       (function(soneId) {
-               setTimeout(function() {
-                       getSoneStatus(soneId, local);
-               }, 5000);
-       })(soneId);
-}
-
 /**
  * Enhances a “delete” button so that the confirmation is done on the same page.
  *
- * @param buttonId
- *            The selector of the button
+ * @param button
+ *            The button element
  * @param text
  *            The text to show on the button
  * @param deleteCallback
  *            The callback that actually deletes something
  */
-function enhanceDeleteButton(buttonId, text, deleteCallback) {
-       button = $(buttonId);
+function enhanceDeleteButton(button, text, deleteCallback) {
        (function(button) {
                newButton = $("<button></button>").addClass("confirm").hide().text(text).click(function() {
                        $(this).fadeOut("slow");
@@ -240,22 +186,22 @@ function enhanceDeleteButton(buttonId, text, deleteCallback) {
                                return false;
                        });
                })(button, newButton);
-       })(button);
+       })($(button));
 }
 
 /**
  * Enhances a post’s “delete” button.
  *
- * @param buttonId
- *            The selector of the button
+ * @param button
+ *            The button element
  * @param postId
  *            The ID of the post to delete
  * @param text
  *            The text to replace the button with
  */
-function enhanceDeletePostButton(buttonId, postId, text) {
-       enhanceDeleteButton(buttonId, text, function() {
-               $.getJSON("ajax/deletePost.ajax", { "post": postId, "formPassword": $("#sone #formPassword").text() }, function(data, textStatus) {
+function enhanceDeletePostButton(button, postId, text) {
+       enhanceDeleteButton(button, text, function() {
+               $.getJSON("ajax/deletePost.ajax", { "post": postId, "formPassword": getFormPassword() }, function(data, textStatus) {
                        if (data == null) {
                                return;
                        }
@@ -277,15 +223,15 @@ function enhanceDeletePostButton(buttonId, postId, text) {
 /**
  * Enhances a reply’s “delete” button.
  *
- * @param buttonId
- *            The selector of the button
+ * @param button
+ *            The button element
  * @param replyId
  *            The ID of the reply to delete
  * @param text
  *            The text to replace the button with
  */
-function enhanceDeleteReplyButton(buttonId, replyId, text) {
-       enhanceDeleteButton(buttonId, text, function() {
+function enhanceDeleteReplyButton(button, replyId, text) {
+       enhanceDeleteButton(button, text, function() {
                $.getJSON("ajax/deleteReply.ajax", { "reply": replyId, "formPassword": $("#sone #formPassword").text() }, function(data, textStatus) {
                        if (data == null) {
                                return;
@@ -325,7 +271,7 @@ function generateSoneList(sones) {
        var soneList = "";
        $.each(sones, function() {
                if (soneList != "") {
-                       soneList += "\n";
+                       soneList += "";
                }
                soneList += this.name;
        });
@@ -344,21 +290,29 @@ function getSoneId(element) {
 }
 
 function getPostElement(element) {
-       return $(element).parents(".post");
+       return $(element).closest(".post");
 }
 
 function getPostId(element) {
        return getPostElement(element).attr("id");
 }
 
+function getPostTime(element) {
+       return getPostElement(element).find(".post-time").text();
+}
+
 function getReplyElement(element) {
-       return $(element).parents(".reply");
+       return $(element).closest(".reply");
 }
 
 function getReplyId(element) {
        return getReplyElement(element).attr("id");
 }
 
+function getReplyTime(element) {
+       return getReplyElement(element).find(".reply-time").text();
+}
+
 function likePost(postId) {
        $.getJSON("ajax/like.ajax", { "type": "post", "post" : postId, "formPassword": getFormPassword() }, function(data, textStatus) {
                if ((data == null) || !data.success) {
@@ -482,6 +436,109 @@ function getReply(replyId, callbackFunction) {
 }
 
 /**
+ * Ajaxifies the given post by enhancing all eligible elements with AJAX.
+ *
+ * @param postElement
+ *            The post element to ajaxify
+ */
+function ajaxifyPost(postElement) {
+       $(postElement).find("form").submit(function() {
+               return false;
+       });
+       $(postElement).find(".create-reply button:submit").click(function() {
+               inputField = $(this.form).find(":input:enabled").get(0);
+               postId = getPostId(this);
+               text = $(inputField).val();
+               $(inputField).val("");
+               postReply(postId, text, function(success, error, replyId) {
+                       if (success) {
+                               loadNewReply(replyId);
+                               markPostAsKnown(getPostElement(inputField));
+                               $("#sone .post#" + postId + " .create-reply").addClass("hidden");
+                       } else {
+                               alert(error);
+                       }
+               });
+               return false;
+       });
+
+       /* replace all “delete” buttons with javascript. */
+       (function(postElement) {
+               getTranslation("WebInterface.Confirmation.DeletePostButton", function(deletePostText) {
+                       postId = getPostId(postElement);
+                       enhanceDeletePostButton($(postElement).find(".delete-post button"), postId, deletePostText);
+               });
+       })(postElement);
+
+       /* convert all “like” buttons to javascript functions. */
+       $(postElement).find(".like-post").submit(function() {
+               likePost(getPostId(this));
+               markPostAsKnown(getPostElement(this));
+               return false;
+       });
+       $(postElement).find(".unlike-post").submit(function() {
+               unlikePost(getPostId(this));
+               markPostAsKnown(getPostElement(this));
+               return false;
+       });
+
+       /* add “comment” link. */
+       addCommentLink(getPostId(postElement), postElement, $(postElement).find(".post-status-line .time"));
+
+       /* process all replies. */
+       $(postElement).find(".reply").each(function() {
+               ajaxifyReply(this);
+       });
+
+       /* process reply input fields. */
+       getTranslation("WebInterface.DefaultText.Reply", function(text) {
+               $(postElement).find("input.reply-input").each(function() {
+                       registerInputTextareaSwap(this, text, "text", false, false);
+               });
+       });
+
+       /* mark everything as known on click. */
+       $(postElement).click(function() {
+               markPostAsKnown(this);
+       });
+
+       /* hide reply input field. */
+       $(postElement).find(".create-reply").addClass("hidden");
+}
+
+/**
+ * Ajaxifies the given reply element.
+ *
+ * @param replyElement
+ *            The reply element to ajaxify
+ */
+function ajaxifyReply(replyElement) {
+       $(replyElement).find(".like-reply").submit(function() {
+               likeReply(getReplyId(this));
+               markPostAsKnown(getPostElement(this));
+               return false;
+       });
+       $(replyElement).find(".unlike-reply").submit(function() {
+               unlikeReply(getReplyId(this));
+               markPostAsKnown(getPostElement(this));
+               return false;
+       });
+       (function(replyElement) {
+               getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(deleteReplyText) {
+                       $(replyElement).find(".delete-reply button").each(function() {
+                               enhanceDeleteReplyButton(this, getReplyId(replyElement), deleteReplyText);
+                       });
+               });
+       })(replyElement);
+       addCommentLink(getPostId(replyElement), replyElement, $(replyElement).find(".reply-status-line .time"));
+
+       /* mark post and all replies as known on click. */
+       $(replyElement).click(function() {
+               markPostAsKnown(getPostElement(replyElement));
+       });
+}
+
+/**
  * Ajaxifies the given notification by replacing the form with AJAX.
  *
  * @param notification
@@ -502,12 +559,14 @@ function ajaxifyNotification(notification) {
        return notification;
 }
 
-/**
- * Retrieves all changed notifications.
- */
-function getNotifications() {
-       $.getJSON("ajax/getNotifications.ajax", {}, function(data, textStatus) {
+function getStatus() {
+       $.getJSON("ajax/getStatus.ajax", {}, function(data, textStatus) {
                if ((data != null) && data.success) {
+                       /* process Sone information. */
+                       $.each(data.sones, function(index, value) {
+                               updateSoneStatus(value.id, value.name, value.status, value.modified, value.locked, value.lastUpdated);
+                       });
+                       /* process notifications. */
                        $.each(data.notifications, function(index, value) {
                                oldNotification = $("#sone #notification-area .notification#" + value.id);
                                notification = ajaxifyNotification(createNotification(value.id, value.text, value.dismissable)).hide();
@@ -517,19 +576,138 @@ function getNotifications() {
                                        $("#sone #notification-area").append(notification);
                                        notification.slideDown();
                                }
+                               setActivity();
                        });
                        $.each(data.removedNotifications, function(index, value) {
                                $("#sone #notification-area .notification#" + value.id).slideUp();
                        });
-                       setTimeout(getNotifications, 5000);
+                       /* process new posts. */
+                       $.each(data.newPosts, function(index, value) {
+                               loadNewPost(value);
+                       });
+                       /* process new replies. */
+                       $.each(data.newReplies, function(index, value) {
+                               loadNewReply(value);
+                       });
+                       /* do it again in 5 seconds. */
+                       setTimeout(getStatus, 5000);
                } else {
-                       setTimeout(getNotifications, 30000);
+                       /* data.success was false, wait 30 seconds. */
+                       setTimeout(getStatus, 30000);
                }
        }, function(xmlHttpRequest, textStatus, error) {
-               /* ignore error. */
+               /* something really bad happend, wait a minute. */
+               setTimeout(getStatus, 60000);
+       })
+}
+
+var loadedPosts = {};
+var loadedReplies = {};
+
+function loadNewPost(postId) {
+       if (postId in loadedPosts) {
+               return;
+       }
+       loadedPosts[postId] = true;
+       $.getJSON("ajax/getPost.ajax", { "post" : postId }, function(data, textStatus) {
+               if ((data != null) && data.success) {
+                       var firstOlderPost = null;
+                       $("#sone .post").each(function() {
+                               if (getPostTime(this) < data.post.time) {
+                                       firstOlderPost = $(this);
+                                       return false;
+                               }
+                       });
+                       newPost = $(data.post.html).addClass("hidden");
+                       if (firstOlderPost != null) {
+                               newPost.insertBefore(firstOlderPost);
+                       } else {
+                               $("#sone #posts").append(newPost);
+                       }
+                       ajaxifyPost(newPost);
+                       newPost.slideDown();
+                       setActivity();
+               }
+       });
+}
+
+function loadNewReply(replyId) {
+       if (replyId in loadedReplies) {
+               return;
+       }
+       loadedReplies[replyId] = true;
+       $.getJSON("ajax/getReply.ajax", { "reply": replyId }, function(data, textStatus) {
+               /* find post. */
+               if ((data != null) && data.success) {
+                       $("#sone .post#" + data.reply.postId).each(function() {
+                               var firstNewerReply = null;
+                               $(this).find(".replies .reply").each(function() {
+                                       if (getReplyTime(this) > data.reply.time) {
+                                               firstNewerReply = $(this);
+                                               return false;
+                                       }
+                               });
+                               newReply = $(data.reply.html).addClass("hidden");
+                               if (firstNewerReply != null) {
+                                       newReply.insertBefore(firstNewerReply);
+                               } else {
+                                       if ($(this).find(".replies .create-reply")) {
+                                               $(this).find(".replies .create-reply").before(newReply);
+                                       } else {
+                                               $(this).find(".replies").append(newReply);
+                                       }
+                               }
+                               ajaxifyReply(newReply);
+                               newReply.slideDown();
+                               setActivity();
+                       });
+               }
        });
 }
 
+function markPostAsKnown(postElements) {
+       $(postElements).each(function() {
+               postElement = this;
+               if ($(postElement).hasClass("new")) {
+                       (function(postElement) {
+                               $.getJSON("ajax/markPostAsKnown.ajax", {"formPassword": getFormPassword(), "post": getPostId(postElement)}, function(data, textStatus) {
+                                       $(postElement).removeClass("new");
+                               });
+                       })(postElement);
+               }
+       });
+       markReplyAsKnown($(postElements).find(".reply"));
+}
+
+function markReplyAsKnown(replyElements) {
+       $(replyElements).each(function() {
+               replyElement = this;
+               if ($(replyElement).hasClass("new")) {
+                       (function(replyElement) {
+                               $.getJSON("ajax/markReplyAsKnown.ajax", {"formPassword": getFormPassword(), "reply": getReplyId(replyElement)}, function(data, textStatus) {
+                                       $(replyElement).removeClass("new");
+                               });
+                       })(replyElement);
+               }
+       });
+}
+
+function resetActivity() {
+       title = document.title;
+       if (title.indexOf('(') == 0) {
+               document.title = title.substr(title.indexOf(' ') + 1);
+       }
+}
+
+function setActivity() {
+       if (!focus) {
+               title = document.title;
+               if (title.indexOf('(') != 0) {
+                       document.title = "(!) " + title;
+               }
+       }
+}
+
 /**
  * Creates a new notification.
  *
@@ -551,3 +729,134 @@ function createNotification(id, text, dismissable) {
        notification.append(text);
        return notification;
 }
+
+//
+// EVERYTHING BELOW HERE IS EXECUTED AFTER LOADING THE PAGE
+//
+
+var focus = true;
+
+$(document).ready(function() {
+
+       /* this initializes the status update input field. */
+       getTranslation("WebInterface.DefaultText.StatusUpdate", function(defaultText) {
+               registerInputTextareaSwap("#sone #update-status .status-input", defaultText, "text", false, false);
+               $("#sone #update-status").submit(function() {
+                       text = $(this).find(":input:enabled").val();
+                       $.getJSON("ajax/createPost.ajax", { "formPassword": getFormPassword(), "text": text }, function(data, textStatus) {
+                               if ((data != null) && data.success) {
+                                       loadNewPost(data.postId);
+                               }
+                       });
+                       $(this).find(":input:enabled").val("").blur();
+                       return false;
+               });
+       });
+
+       /* ajaxify input field on “view Sone” page. */
+       getTranslation("WebInterface.DefaultText.Message", function(defaultText) {
+               registerInputTextareaSwap("#sone #post-message input[name=text]", defaultText, "text", false, false);
+               $("#sone #post-message").submit(function() {
+                       text = $(this).find(":input:enabled").val();
+                       $.getJSON("ajax/createPost.ajax", { "formPassword": getFormPassword(), "recipient": $("#sone #sone-id").text(), "text": text }, function(data, textStatus) {
+                               if ((data != null) && data.success) {
+                                       loadNewPost(data.postId);
+                               }
+                       });
+                       $(this).find(":input:enabled").val("").blur();
+                       return false;
+               });
+       });
+
+       /* Ajaxifies all posts. */
+       /* calling getTranslation here will cache the necessary values. */
+       getTranslation("WebInterface.Confirmation.DeletePostButton", function(text) {
+               getTranslation("WebInterface.Confirmation.DeleteReplyButton", function(text) {
+                       getTranslation("WebInterface.DefaultText.Reply", function(text) {
+                               $("#sone .post").each(function() {
+                                       ajaxifyPost(this);
+                               });
+                       });
+               });
+       });
+
+       /* hides all replies but the latest two. */
+       getTranslation("WebInterface.ClickToShow.Replies", function(text) {
+               $("#sone .post .replies").each(function() {
+                       allReplies = $(this).find(".reply");
+                       if (allReplies.length > 2) {
+                               newHidden = false;
+                               for (replyIndex = 0; replyIndex < (allReplies.length - 2); ++replyIndex) {
+                                       $(allReplies[replyIndex]).addClass("hidden");
+                                       newHidden |= $(allReplies[replyIndex]).hasClass("new");
+                               }
+                               clickToShowElement = $("<div></div>").addClass("click-to-show");
+                               if (newHidden) {
+                                       clickToShowElement.addClass("new");
+                               }
+                               (function(clickToShowElement, allReplies, text) {
+                                       clickToShowElement.text(text);
+                                       clickToShowElement.click(function() {
+                                               allReplies.removeClass("hidden");
+                                               clickToShowElement.addClass("hidden");
+                                       });
+                               })(clickToShowElement, allReplies, text);
+                               $(allReplies[0]).before(clickToShowElement);
+                       }
+               });
+       });
+
+       /*
+        * convert all “follow”, “unfollow”, “lock”, and “unlock” links to something
+        * nicer.
+        */
+       $("#sone .follow").submit(function() {
+               var followElement = this;
+               $.getJSON("ajax/followSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
+                       $(followElement).addClass("hidden");
+                       $(followElement).parent().find(".unfollow").removeClass("hidden");
+               });
+               return false;
+       });
+       $("#sone .unfollow").submit(function() {
+               var unfollowElement = this;
+               $.getJSON("ajax/unfollowSone.ajax", { "sone": getSoneId(this), "formPassword": getFormPassword() }, function() {
+                       $(unfollowElement).addClass("hidden");
+                       $(unfollowElement).parent().find(".follow").removeClass("hidden");
+               });
+               return false;
+       });
+       $("#sone .lock").submit(function() {
+               var lockElement = this;
+               $.getJSON("ajax/lockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
+                       $(lockElement).addClass("hidden");
+                       $(lockElement).parent().find(".unlock").removeClass("hidden");
+               });
+               return false;
+       });
+       $("#sone .unlock").submit(function() {
+               var unlockElement = this;
+               $.getJSON("ajax/unlockSone.ajax", { "sone" : getSoneId(this), "formPassword" : getFormPassword() }, function() {
+                       $(unlockElement).addClass("hidden");
+                       $(unlockElement).parent().find(".lock").removeClass("hidden");
+               });
+               return false;
+       });
+
+       /* process all existing notifications, ajaxify dismiss buttons. */
+       $("#sone #notification-area .notification").each(function() {
+               ajaxifyNotification($(this));
+       });
+
+       /* activate status polling. */
+       setTimeout(getStatus, 5000);
+
+       /* reset activity counter when the page has focus. */
+       $(window).focus(function() {
+               focus = true;
+               resetActivity();
+       }).blur(function() {
+               focus = false;
+       })
+
+});