/* 
 */

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://xwiki.e-li.se:80/wiki/cp4all/save/Blog/__name__?ajax=1&template=Blog.CategoryTemplate&form_token=mdRNz65GTD6DeiQyexbohw".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("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'       : "<span class=\"fa fa-unlock\"><\/span>",
         'comment'    : "Made entry visible",
         'title'      : "This blog post is not visible to other users. Make it visible.",
         'hiddenValue': '1',
         'css'        : 'blog-tool-show'
       },
      'hide': {
        'icon'       : "<span class=\"fa fa-lock\"><\/span>",
        'comment'    : "Hidden entry",
        'title'      : "Hide this blog post from other users.",
        '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("This blog post is hidden.");
        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("Changing the visibility", '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("The visibility of the blog entry has been successfully changed", 'done');
      })
      /**
       * On error
       */
      .fail(function (jqXHR, textStatus, errorThrown) {
        if (jqXHR.statusCode() == 403) {
          new XWiki.widgets.Notification("You are not allowed to create the target page", 'error');
        } else if (jqXHR.statusCode() == 401) {
          new XWiki.widgets.Notification("You have been logged out, please refresh and log in", 'error');
        } else {
          new XWiki.widgets.Notification("Failed to change blog post visibility.", 'error');
        }
      })
      /**
       * Always
       */
      .always(function () {
        loadingMessage.hide();
        // Show the link again
        link.show();
      });
    };
    
    /**
     * Initialize the blog entries toolbar.
     */
    $('.blog-tool-show,.blog-tool-hide').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"));
    });
    
  });

});

