require(['jquery', 'xwiki-events-bridge'], function ($) {
  'use strict';
  
  /**
   * Add a 'launch tour' button into the 'actions' columns.
   */
  var addLaunchButton = function (row) {
    // Do not add the button if the tour is not active or if the target page is not set
    if (row.find('.targetPage').text() == '-' || row.find('.isActive').text() != 'J\u0101') {
        return;
    }
    var targetPage = XWiki.Model.resolve(row.find('.targetPage').text(), XWiki.EntityType.DOCUMENT);
    var targetPageDocument;
    // Two behaviours depending of the handling of the Nested Pages feature.
    if (XWiki.Document.initializeFromReference) {
      targetPageDocument = new XWiki.Document(targetPage);
    } else {
      targetPageDocument = new XWiki.Document(targetPage.name,
        targetPage.extractReferenceValue(XWiki.EntityType.SPACE));
    }
    
    // Add a launch tour link to the actions column.
    if (row.find('.actionLaunch').length == 0) {
      $('<a class="action actionLaunch"><span class="fa fa-play"></span> Launch</a>')
        .attr('href', targetPageDocument.getURL('view', 'startTour=true'))
        .css('padding-left', '1px').appendTo(row.find('.actions'));
    }
  }
  
  /**
   * Add the launch button into each livetable raw.
   */
  var initLivetableResults = function () {
    $('#tour tr').each( function() {
      addLaunchButton($(this));
    });
  }
  $(document).on('xwiki:livetable:ready', initLivetableResults);
  $(document).ready(initLivetableResults);
  
  /**
   * Add the launch button into each new livetable raw.
   */
  $(document).on('xwiki:livetable:newrow', function (event, data) {
    // It only concerns the 'tour' livetable
    if (data.tableId != 'tour') {
      // This is to be extra sure, but there should not be other livetables in that page...
      return;
    }
    addLaunchButton($(data.row));
  });
  
});

