/* {pre}{/pre}
 */

if(typeof(XWiki) == 'undefined') {
  XWiki = new Object();
}
XWiki.Blog = {
  blogToolsValues: {
    show: {
      title: "This blog post is not visible to other users. Make it visible",
      imageSrc: "/kiaora%2Dng/bin/download/Blog/BlogStyle/show.png",
      imageAlt: "show",
      comment: "Made%20entry%20visible"
    },
    hide: {
      title: "Hide this blog post from other users",
      imageSrc: "/kiaora%2Dng/bin/download/Blog/BlogStyle/hide.png",
      imageAlt: "hide",
      comment: "Hidden%20entry"
    },
    loading: {
      title: "Loading...",
      imageSrc: "/kiaora%2Dng/bin/download/Blog/BlogStyle/ajax%2Dloader.gif",
      imageAlt: "loading"
    }
  },

  initialize : function() {
    XWiki.Blog.addBehaviorToBlogTools();
    XWiki.Blog.addBehaviorToNewPostForm();
  },

  addBehaviorToBlogTools : function() {
    $$(".blog-tool-hide").each(function(button) {
      button.blogCallback = XWiki.Blog.makeEntryInvisible.bindAsEventListener(button);
    });
    $$(".blog-tool-show").each(function(button) {
      button.blogCallback = XWiki.Blog.makeEntryVisible.bindAsEventListener(button);
    });
    $$(".blog-tool-show, .blog-tool-hide").each(function(button) {
      button.href = button.href.replace(/&xredirect=.*?(&|$)/, "&ajax=1$1");
      Event.observe(button, "click", XWiki.Blog.linkDisabler.bindAsEventListener(button));
      Event.observe(button, "click", button.blogCallback);
    });
    var addCategoryButton = $("blog_AddCategoryButton");
    if (addCategoryButton) {
      Event.observe(addCategoryButton, "click", XWiki.Blog.createBlogCategory.bindAsEventListener(addCategoryButton.form));
    }
  },

  addBehaviorToNewPostForm : function() {
    var form = $("newBlogPost");
    if (form) {
      Event.observe(form, "submit", function() {
        form.action="/kiaora%2Dng/bin/inline/__space__/__name__".replace(/__space__/, encodeURIComponent(form.space.value)).replace(/__name__/, encodeURIComponent(form.title.value));
      });
      var title = form.elements.namedItem("entryTitle");
      if (title) {
        Event.observe(title, "focus", function() {
          if(title.value == title.defaultValue) {
            title.value = "";
          } else {
            title.select();
          }
        });
        Event.observe(title, "blur", function() {
          if(title.value == "") {
            title.value = title.defaultValue;
          }
        });
      }
    }
  },

  makeEntryInvisible : function(event) {
    Event.stopObserving(this, "click", this.blogCallback);
    XWiki.Blog.setToolLoadingStatus(this, XWiki.Blog.blogToolsValues.loading);
    new Ajax.Request(this.href, {
      method: "get",
      onSuccess: XWiki.Blog.onEntryMadeInvisible.bind(this)
    });
  },
  makeEntryVisible : function(event) {
    Event.stopObserving(this, "click", this.blogCallback);
    XWiki.Blog.setToolLoadingStatus(this, XWiki.Blog.blogToolsValues.loading);
    new Ajax.Request(this.href, {
      method: "get",
      onSuccess: XWiki.Blog.onEntryMadeVisible.bind(this)
    });
  },
  onEntryMadeVisible : function() {
    var entry = XWiki.Blog.getEntry(this);
    if (entry) {
      XWiki.Blog.setEntryVisibility(entry, true);
    }
    XWiki.Blog.updateShowHideButton(this, XWiki.Blog.blogToolsValues.hide);
    this.blogCallback = XWiki.Blog.makeEntryInvisible.bindAsEventListener(this);
    Event.observe(this, "click", this.blogCallback);
    $$(".entry-content").each(function(content) {
      content.previous(".warningmessage").hide();
    });
  },
  onEntryMadeInvisible : function() {
    var entry = XWiki.Blog.getEntry(this);
    if (entry && !entry.hasClassName("single-article")) {
      XWiki.Blog.setEntryVisibility(entry, false);
    }
    XWiki.Blog.updateShowHideButton(this, XWiki.Blog.blogToolsValues.show);
    this.blogCallback = XWiki.Blog.makeEntryVisible.bindAsEventListener(this);
    Event.observe(this, "click", this.blogCallback);
    $$(".entry-content").each(function(content) {
      if(content.previous(".warningmessage")) {
        content.previous(".warningmessage").show();
      } else {
        // <div class="warningmessage"><span class="messagetype">Warning: </span>This blog post is hidden.</div>
        var wrapper = document.createElement("div").addClassName("warningmessage");
        var label = document.createElement("span").addClassName("messagetype");
        label.appendChild(document.createTextNode("Warning: "));
        wrapper.appendChild(label);
        wrapper.appendChild(document.createTextNode("This blog post is hidden."));
        content.up().insertBefore(wrapper, content);
      }
    });
  },

  updateShowHideButton : function(button, resources) {
    button.title = resources.title;
    button.down("img").src = resources.imageSrc;
    button.down("img").alt = resources.alt;
    button.href = button.href.replace(/&comment=(.*?)(&|$)/, "&comment=" + resources.comment + "$2");
    if (button.href.match(/_hidden=1/)) {
      button.href = button.href.replace(/_hidden=1/, "_hidden=0");
    } else {
      button.href = button.href.replace(/_hidden=0/, "_hidden=1");
    }
  },
  getEntry : function(startElement) {
    return startElement.up(".hentry");
  },
  setEntryVisibility : function(entry, visible) {
    if (visible) {
      entry.removeClassName("hidden-article");
    } else {
      entry.addClassName("hidden-article");
    }
  },
  setToolLoadingStatus : function(button, resources) {
    button.title = resources.title;
    button.down("img").src = resources.imageSrc;
    button.down("img").alt = resources.alt;
  },
  linkDisabler : function(event) {
    Event.stop(event);
  },
  createBlogCategory : function() {
    var name = this.newCategoryName.value;
    var safeName = encodeURI(name.replace(/'/g, "").replace(/"/g, ""));
    var title = encodeURI(name);
    var parentCategory = this.newCategoryParent.value;
    var parentSpace = encodeURI(parentCategory.substring(0, parentCategory.indexOf(".")));
    var parent = encodeURI(parentCategory);
    new Ajax.Request("/kiaora%2Dng/bin/save/Blog/__name__?ajax=1&template=Blog.CategoryTemplate".replace(/__name__/g, safeName) + "&parent=" + parent + "&title=" + title + "&Blog.CategoryClass_0_name=" + title, {
      method: "get",
      onSuccess: XWiki.Blog.updateCategoryTree.bindAsEventListener(this, name, parentCategory, parentSpace),
      onFailure: function() {alert("This category already exists.")}
    });
  },

  updateCategoryTree : function(event, name, parentCategory, parentSpace) {
    var parentElement = $("blog_category_" + parentCategory);
    if (!parentElement) {
      parentElement = $("blog_category_container");
    } else {
      parentElement = parentElement.up();
    }
    var parentUl = parentElement.down("ul");
    if (!parentUl) {
      parentUl = document.createElement("ul");
      parentElement.appendChild(parentUl);
    }
    var children = parentUl.childElements();
    var found = false;
    var myId = "blog_category_" + parentSpace + "." + name;
    var li = document.createElement("li");
    var label = document.createElement("label");
    label.id = myId;
    li.appendChild(label);
    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.checked = "checked";
    checkbox.name = "Blog.BlogPostClass_0_category";
    checkbox.value = parentSpace + "." + name;
    label.appendChild(checkbox);
    label.appendChild(document.createTextNode(" " + name));
    var option = document.createElement("option");
    option.id = myId + "_option";
    option.value = parentSpace + "." + name;
    var depth = 0;
    var tmpParent = parentElement;
    while(tmpParent && tmpParent != $("blog_category_container")) {
      depth++;
      tmpParent = tmpParent.up("li");
    }
    option.appendChild(document.createTextNode("&nbsp;".unescapeHTML().times(2*depth) + name)); // TODO: Indent
    var selectBox = $("blog_category_selectBox");
    for (var i = 0; i < children.size(); ++i) {
      if (children[i].down("label").id > myId) {
        parentUl.insertBefore(li, children[i]);
        var optionSibling = $(children[i].down("label").id + "_option");
        selectBox.insertBefore(option, optionSibling);
        found = true;
        break;
      }
    }
    if (!found) {
      parentUl.appendChild(li);
      var tmpParent = parentElement;
      var optionAfter;
      while (!optionAfter && tmpParent) {
        optionAfter = tmpParent.next("li");
        tmpParent = tmpParent.up("li")
      }
      if (optionAfter) {
        selectBox.insertBefore(option, $(optionAfter.down("label").id + "_option"));
      } else {
        selectBox.appendChild(option);
      }
    }
  }
}

function publishEntry(publishServiceName, blogPostName, sourceElement) {
  new Ajax.Request("/kiaora%2Dng/bin/view/Blog/__name__".replace(/__name__/g, publishServiceName) + "?entryName=" + blogPostName, {method: "get", onSuccess: function() {alert("done");
  sourceElement.parentNode.removeChild(sourceElement);}});
  return false;
}
document.observe("dom:loaded", XWiki.Blog.initialize);
