/**
 * @file
 *
 * Behaviors for every comment reply link on forum pages.
 *
 * Topic toggler on non first page of forum topics.
 */
 
/**
 * Forum topic comment reply link behaviors.
 *
 * The links can be attached to the topic, or to comments, they have the class: `comment_reply`.
 *
 * @param context
 *   In which the behavior should be added.
 */
Drupal.behaviors.npForumCommentReply = function (context) {
  var links;
  if (context != document) {
    links = $('body.nodetype-forum').andSelf().find(context).andSelf().find('a.comment_reply');
  }
  else {
    links = $('body.nodetype-forum a.comment_reply');
  }
  links = links.not('.comment-reply-processed').filter('[href*="/comment/reply"]').addClass('comment-reply-processed');
  if (links.size()) {
    var matches; // Parts of the link's `href` will be stored here from .match()
    var title; // Comment dialog title.

    /**
     * Handle Comment form loaded event.
     *
     * Prepare some styling, behaviors, and some DOM manipulation.
     */
    var formLoaded = function () {
      // Style up the form.
      var submitting = false;
      $(this).find("form:first").submit(function () {
        if (submitting) {
          return false;
        }
        $(this).find(':submit').css('color', '#7E8082');
        submitting = true;
      }).find('div.wrapper-4b4:first').removeClass('wrapper-4b4').addClass('wrapper-111').find(
        'input#edit-submit').removeClass('button-01-l').addClass(
        'button-07-l');
      // Prepare the HTMLBox on the comment text.
      $(this).find('textarea#edit-comment').attr(
        'id', 'edit-comment-'+ Math.round(Math.random() * 0xFFFFFF)).htmlbox().button("bold").button(
        "italic").separator("dots").button("hyperlink").separator(
        "dots").button("ul").button("ol").button("html").separator(
        "dots").button("indent").button("outdent").separator("dots").init();
      // Move the dialog title into the form title.
      $(this).parents('.ui-dialog:first').find(
        '.ui-dialog-titlebar').prependTo($(this).find('h2.comments').addClass('clearfix').html(title));
    };
    
    var container = $('<div class="wrapper-xxx">\
      <span class="corner-top"></span><span class="corner-bottom"></span>\
      <div class="form-add-comment"></div>\
      <span class="corner-bottom"></span><span class="corner-top"></span>\
    </div>').dialog(
      {
        'draggable': false,
        'autoOpen':  false,
        'modal':     true,
        'minHeight': 315,
        'height':    'auto',
        'width':     620,
        'overlay':   {
            'background-color': 'black',
            'opacity':          0.7
        },
        'open':      function () {
          // Prepare the dialog title and close button.
          container.parents('.ui-dialog:first').find(
            '.ui-dialog-titlebar').insertBefore(container).find(
            'a.ui-dialog-titlebar-close').html(
            'Close <img class="icon-01-close icon-va-baseline" src="'+
              Drupal.settings.static_url +'graphics/sites/all/themes/nova/default/images/1px.gif"/>');
          container.html($('<img src="'+ Drupal.settings.loading_signal +'" alt="Loading" />').css({
            'margin': '10px'
          }));
          // Load the comment form via AHAH
          container.load("/forum/ahah/comment/"+ matches[1] +'/'+ (matches[2] ? matches[2] : 0), {}, formLoaded);
        }
      }).find(".form-add-comment");

    links.click(function () {
      // Gather components from the links `href`.
      matches = this.href.match(/\/comment\/reply\/(\d+)(?:\/(\d+))?/);
      if (matches) {
        // If it is a topic, then the last item of the match is undefined (or may be 0).
        title = matches[2] && matches[2] != '0' ?
          'Reply to post by:' :
          'Add a post to:';
        // Gather the items for the title.
        var items = matches[2] && matches[2] != '0' ?
          $(this).parents('div.hentry:first').find('div.content-info').children().not('div.icons') :
          $(this).parents('div.hentry:first').find('h2.entry-title');
        title += '<em>';
        items.each(function () {
          title += " "+ $(this).text();
        });
        title += '</em>';

        container.parent().dialog("open");
        return false;
      }
    });
  }
};

/**
 * Forum topic details toggler on non first page of the forum topic.
 *
 * The topic is in a div with class `hentry`, and has a tag with class `content-can-close`.
 *
 * @param context
 *   In which the behavior should be added.
 */
Drupal.behaviors.npForumTopicToggle = function (context) {
  var content;
  if (context != document) {
    content = $('body.nodetype-forum').andSelf().find(context).andSelf().find('div.hentry');
  }
  else {
    content = $('body.nodetype-forum div.hentry');
  }
  
  // Prepare the toggle continer, and the clickable interface to toggle.
  content.find('.content-can-close').not(
    '.topic-toggle-processed').addClass('topic-toggle-processed').hide().before($('<div class="wrapper-body content-toggler"><div><span>Show Topic</span> <img class="arrow-02-d6" src="'+ Drupal.settings.static_url +'graphics/sites/all/themes/nova/default/images/1px.gif"/></div></div>').click(function () {
      // Open / close the container, change the interface according to current state.
      $(this).siblings('.topic-toggle-processed').slideToggle('normal', function () {
        var visible = $(this).is(':visible');
        $(this).siblings('.content-toggler').find('div span').text(visible ? 'Hide Topic' : 'Show Topic').end().find('img').removeClass().addClass(visible ? 'arrow-02-u6' : 'arrow-02-d6');
      });
      return false;
    }));
};

/**
 * @param context
 *   In which the behavior should be added.
 */
Drupal.behaviors.npForumNoticeChanger = function (context) {
  $('div.forum-navigation div.forum-edit-notice:not(.forum-notice-changer-processed)').addClass(
    'forum-notice-changer-processed').find('a[href*="/forum/notice"]').click(function () {
    var url = this.href.replace(/\/forum\/notice/, '/forum/ahah/notice');

    /**
     * Handle Form loaded event.
     */
    var formLoaded = function () {
      $(this).find('textarea#edit-notice').attr(
        'id', 'edit-notice-'+ Math.round(Math.random() * 0xFFFFFF)).htmlbox().button("bold").button(
        "italic").separator("dots").button("hyperlink").separator(
        "dots").button("ul").button("ol").button("html").separator(
        "dots").button("indent").button("outdent").separator("dots").init();
    };

    var container = $('<div class="wrapper-xxx">\
      <span class="corner-top"></span><span class="corner-bottom"></span>\
      <div class="form-add-comment"></div>\
      <span class="corner-bottom"></span><span class="corner-top"></span>\
    </div>').dialog(
      {
        'draggable': false,
        'autoOpen':  false,
        'modal':     true,
        'minHeight': 315,
        'height':    'auto',
        'width':     620,
        'overlay':   {
            'background-color': 'black',
            'opacity':          0.7
        },
        'open':      function () {
          // Prepare the dialog title and close button.
          container.parents('.ui-dialog:first').find(
            '.ui-dialog-titlebar').insertBefore(container).find(
            'a.ui-dialog-titlebar-close').html(
            'Close <img class="icon-01-close icon-va-baseline" src="'+
              Drupal.settings.static_url +'graphics/sites/all/themes/nova/default/images/1px.gif"/>');
          container.html($('<img src="'+ Drupal.settings.loading_signal +'" alt="Loading" />').css({
            'margin': '10px'
          }));
          // Load the comment form via AHAH
          container.load(url, {}, formLoaded);
        }
      }).find(".form-add-comment");
      container.parent().dialog("open");
      return false;
    });
};
;