/* 
 */

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: "resources/icons/silk/lock_open.png",
      imageAlt: "show",
      comment: "Made entry visible"
    },
    hide: {
      title: "Hide this blog post from other users.",
      imageSrc: "resources/icons/silk/lock.png",
      imageAlt: "hide",
      comment: "Hidden entry"
    },
    loading: {
      title: "Loading...",
      imageSrc: "resources/icons/xwiki/spinner.gif",
      imageAlt: "loading"
    }
  },

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

  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));
    }
  },

  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),
      on1223: function(response) {response.request.options.onSuccess(response)},
      on403: function() {alert("You are not allowed to create the target page")},
      on401: function() {alert("You have been logged out, please refresh and log in")},
      onFailure: function() {alert("Failed to change blog post visibility.")}
    });
  },
  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),
      on1223: function(response) {response.request.options.onSuccess(response)},
      on403: function() {alert("You are not allowed to create the target page")},
      on401: function() {alert("You have been logged out, please refresh and log in")},
      onFailure: function() {alert("Failed to change blog post visibility.")}
    });
  },
  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=" + encodeURIComponent(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("http://dietpanda.com/xwiki/bin/save/Blog/__name__?ajax=1&template=Blog.CategoryTemplate&form_token=hqJdIbORgYtngBUDs6ybZA".replace(/__name__/g, safeName) + "&parent=" + parent + "&title=" + title + "&Blog.CategoryClass_0_name=" + title, {
      method: "get",
      onSuccess: XWiki.Blog.updateCategoryTree.bindAsEventListener(this, name, parentCategory, parentSpace),
      on1223: function(response) {response.request.options.onSuccess(response)},
      on409: function() {alert("Target page already exists, please choose a different name")},
      on403: function() {alert("You are not allowed to create the target page")},
      on401: function() {alert("You have been logged out, please refresh and log in")},
      onFailure: function() {alert("xe.blog.manageCategories.js.add.failed")}
    });
  },

  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("http://dietpanda.com/xwiki/bin/view/Blog/__name__".replace(/__name__/g, publishServiceName) + "?entryName=" + blogPostName, {method: "get", onSuccess: function() {alert("done");
  sourceElement.parentNode.removeChild(sourceElement);}});
  return false;
}
document.observe("xwiki:dom:loaded", XWiki.Blog.initialize);
