/* 
 */

if(typeof(XWiki) == 'undefined') {
  XWiki = new Object();
}
XWiki.Blog = {
  initialize : function() {
    var addCategoryButton = $("blog_AddCategoryButton");
    if (addCategoryButton) {
      Event.observe(addCategoryButton, "click", XWiki.Blog.createBlogCategory.bindAsEventListener(addCategoryButton.form));
    }
  },

  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("https://keqiongpan.cn:80/bin/save/Blog/__name__?ajax=1&template=Blog.CategoryTemplate&form_token=8hCa0btHAF51nFugm0qs8Q".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("\u76EE\u6807\u6587\u6863\u5DF2\u5B58\u5728\uFF0C\u8BF7\u9009\u62E9\u5176\u4ED6\u540D")},
      on403: function() {alert("\u60A8\u4E0D\u80FD\u521B\u5EFA\u76EE\u6807\u6587\u6863")},
      on401: function() {alert("\u60A8\u5DF2\u6CE8\u9500\uFF0C\u8BF7\u5237\u65B0\u540E\u767B\u5F55")},
      onFailure: function() {alert("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);
      }
    }
  }
}
document.observe("xwiki:dom:loaded", XWiki.Blog.initialize);
/**
 * Make the show/hide buttons asynchronous.
 *
 * This code has been rewritten using jQuery and more modern technologies such as the Notification Widget or
 * the Icon Theme Application. The results is more in line with the modern XWiki look & feel.
 */
require(['jquery'], function ($) {
  'use strict';
  
  /**
   * Initialization
   */
  $(document).ready(function() {
  
    /**
     * The different actions that the blog entries toolbars can handle
     */
    var actions = {
      'show': {
         'icon'       : "<img src=\"..\/..\/resources\/icons\/silk\/lock_open.png\" alt=\"Icon\" \/>",
         'comment'    : "\u8BBE\u7F6E\u53EF\u89C1",
         'title'      : "\u8BE5\u535A\u5BA2\u6587\u7AE0\u5BF9\u5176\u4ED6\u7528\u6237\u4E0D\u53EF\u89C1\u3002\u4F7F\u5176\u53EF\u89C1\u3002",
         'hiddenValue': '1',
         'css'        : 'blog-tool-show'
       },
      'hide': {
        'icon'       : "<img src=\"..\/..\/resources\/icons\/silk\/lock.png\" alt=\"Icon\" \/>",
        'comment'    : "\u9690\u85CF\u6B64\u6587",
        'title'      : "\u5BF9\u5176\u4ED6\u7528\u6237\u9690\u85CF\u8BE5\u535A\u5BA2\u6587\u7AE0\u3002",
        'hiddenValue': '0',
        'css'        : 'blog-tool-hide'
      }
    };
    
    /**
     * Actions to perform when a blog entry is shown.
     */
    var onEntryMadeVisible = function (entry) {
      entry.removeClass('hidden-article');
      entry.find('>div.warningmessage').hide();
    };
    
    /**
     * Actions to perform when a blog entry is made hidden.
     */
    var onEntryMadeInvisible = function (entry) {
      if (!entry.hasClass('single-article')) {
        entry.addClass('hidden-article');
      }
      var warningMessage = entry.find('>div.warningmessage');
      if (warningMessage.length > 0) {
        warningMessage.show();
      } else {
        warningMessage = $('<div>').addClass('box').addClass('warningmessage');
        warningMessage.text("\u8BE5\u535A\u5BA2\u6587\u7AE0\u5DF2\u9690\u85CF\u3002");
        warningMessage.insertBefore(entry.find('.entry-content'));
      }
    };

    /**
     * Hide/Show entries on click
     */
    var hideShowEntry = function (event) {
     // Don't let the browser fetch the normal link
     event.preventDefault();
     // Get the current object
     var link = $(this);
     // Get the corresponding entry
     var entry = link.parents('.hentry');
     // Hide the link to avoid clicking again on it by mistake during the process
     link.hide();
     // What is the current action that we need to perform
     var currentAction = link.hasClass('blog-tool-hide') ? 'hide' : 'show';
     // We will replace the current link by a new one corresponding to a new action:
     var newAction = currentAction == 'hide' ? actions.show : actions.hide;
     // Display a message while the ajax request is proceeded
     var loadingMessage = new XWiki.widgets.Notification("\u6539\u53D8\u53EF\u89C1\u6027", 'inprogress');
     
     // Perform an ajax query to show/hide the entry.
     $.ajax(link.attr('href'))
       /**
        * On Success
        */
      .done(function() {
        // Replace the icon
        link.find('span.icon-manage').html(newAction.icon);
        // Replace the URL of the link
        var url = link.attr('href').replace(/&comment=(.*?)(&|$)/, "&comment=" + encodeURIComponent(newAction.comment) + "$2");
        url = url.replace(/_hidden=./, '_hidden=' + newAction.hiddenValue);
        link.attr('href', url);
        // Replace the title of the link
        link.attr('title', newAction.title);
        // Replace the css class of the link
        link.attr('class', newAction.css);
        
        if (currentAction == 'hide') {
          onEntryMadeInvisible(entry);
        } else {
          onEntryMadeVisible(entry);
        }
        
        // Display the success message
        new XWiki.widgets.Notification("\u535A\u5BA2\u6761\u76EE\u7684\u53EF\u89C1\u6027\u5DF2\u6210\u529F\u66F4\u6539", 'done');
      })
      /**
       * On error
       */
      .fail(function (jqXHR, textStatus, errorThrown) {
        if (jqXHR.statusCode() == 403) {
          new XWiki.widgets.Notification("\u60A8\u4E0D\u80FD\u521B\u5EFA\u76EE\u6807\u6587\u6863", 'error');
        } else if (jqXHR.statusCode() == 401) {
          new XWiki.widgets.Notification("\u60A8\u5DF2\u6CE8\u9500\uFF0C\u8BF7\u5237\u65B0\u540E\u767B\u5F55", 'error');
        } else {
          new XWiki.widgets.Notification("\u9519\u8BEF\uFF1A\u65E0\u6CD5\u66F4\u6539\u535A\u6587\u7684\u53EF\u89C1\u6027\u3002", 'error');
        }
      })
      /**
       * Always
       */
      .always(function () {
        loadingMessage.hide();
        // Show the link again
        link.show();
      });
    };
    
    /**
     * Initialize the blog entries toolbar.
     */
    $('.blog-tool-show,.blog-tool-hide').on('click', hideShowEntry).each(function () {
      // Add "ajax=1" to the URL of the toolbar links
      var link = $(this);
      link.attr('href', link.attr('href').replace(/xredirect=.*?(&|$)/, "ajax=1$1"));
    });
    
  });

});

