var bstStepURL = "https://wiki.rtsys.informatik.uni-kiel.de/bin/edit/TourCode/StepSheet?editor=inline&xpage=plain";
var messages   = {  deleting: "Deleting step...",
                    deleteConfirm: "Are you sure you want to delete the step?",
                    deleteDone: "Delete step done!"
                 }

require(['jquery', 'xwiki-meta'], function ($, xm) {
  'use strict';

  // Initialize add new step button
  $('#addStep').on('click', function() {
    var tourName = $('#tourName').val();
    $('.xdialog-modal-container').remove();
    new XWiki.widgets.StepPopup({pageURL: bstStepURL + '&tourName=' + tourName});
  });

  // Initialize save step button
  $('body').on('click', '#saveStepBtn', function() {
    var parent = $(this).parent().parent();
    var stepID = $('#stepID', parent).val();
    var prefix = 'TourCode.StepClass_';
    var tourName = $("#tourName",parent).val();
    var element = $("input[id^='" + prefix + "'][id$='_element']", parent).val();
    var title = $("input[id^='" + prefix + "'][id$='_title']", parent).val();
    var backdrop = $("input[id^='" + prefix + "'][id$='_backdrop']", parent).is(':checked');
    var content = $("textarea[id^='" + prefix + "'][id$='_content']", parent).val();
    var placement = $("select[id^='" + prefix + "'][id$='_placement']", parent).val();
    var targetPage = $("input[id^='" + prefix + "'][id$='_targetPage']", parent).val(); 
    var targetAction = $("input[id^='" + prefix + "'][id$='_action']", parent).val(); 
    var queryString = $("input[id^='" + prefix + "'][id$='_queryString']", parent).val();
    var reflex = $("input[id^='" + prefix + "'][id$='_reflex']", parent).is(':checked');
    var stepOrder = $('#stepOrderSelect').val();
    var nbSteps = $('#nbsteps').val();
    var step = {  element     : (element? element: ''),
                  title       : (title? title: ''),
                  backdrop    : backdrop,
                  content     : (content? content: ''),
                  placement   : (placement? placement: ''),
                  targetPage  : (targetPage? targetPage: ''),
                  targetAction: (targetAction? targetAction: ''),
                  queryString : (queryString? queryString: ''),
                  reflex      : reflex,
                  stepOrder   : (stepOrder? stepOrder: ''),
                  tourName    : (tourName? tourName: ''),
                  nbSteps     : nbSteps,
                  stepID      : stepID,
                  action      : 'editStep',
                  xpage       : 'plain'
               };
    $.ajax({
      url : "https://wiki.rtsys.informatik.uni-kiel.de/bin/view/TourCode/AjaxActions",
      type: 'POST',
      data: step,
      success: function(rep) {
        $('#stepsContainer').html(rep);
        if (xm.refreshVersion) {
          xm.refreshVersion();
        }
      },
      complete: function() {
        // Close dialog box
        $('.xdialog-close').click();
      }
    });
  });

  // Initialize step edit btns
  $('body').on('click', '.editStep', function() {
    $('.xdialog-modal-container').remove();
    var tourName = $('#tourName').val();
    var stepID = $(this).attr('data-step-id');
    $('.xdialog-modal-container').remove();
    new XWiki.widgets.StepPopup({
      pageURL: bstStepURL + '&tourName=' + encodeURIComponent(tourName) + '&stepID=' + encodeURIComponent(stepID)
    });
  });
   
  // Initialize step delete btns
  $('body').on('click', '.deleteStep', function() {
    $('.xdialog-modal-container').remove();
    var tourName = $('#tourName').val();
    var stepID = $(this).attr('data-step-id');
    new XWiki.widgets.ConfirmationBox({
      onYes: function() {
        var notif = new XWiki.widgets.Notification(messages.deleting, 'inprogress');
        $.ajax({
          url : "https://wiki.rtsys.informatik.uni-kiel.de/bin/view/TourCode/AjaxActions?xpage=plain" + '&action=deleteStep' + '&tourName=' + encodeURIComponent(tourName) + '&stepID=' + encodeURIComponent(stepID),
          type: 'POST',
          success: function(rep) {
            $('#stepsContainer').html(rep);
            if (xm.refreshVersion) {
              xm.refreshVersion();
            }
          },
          complete: function() {
            notif.replace(new XWiki.widgets.Notification(messages.deleteDone, 'done'));
            //TODO: add "on failure"
          }
        });
      }},
      {
        confirmationText: messages.deleteConfirm
      }
    );
  });
});
// Make sure the XWiki 'namespace' and the ModalPopup class exist.
if(typeof(XWiki) == 'undefined' || typeof(XWiki.widgets) == 'undefined' || typeof(XWiki.widgets.ModalPopup) == 'undefined') {
  if (typeof console != 'undefined' && typeof console.warn == 'function') {
    console.warn('[MessageBox widget] Required class missing: XWiki.widgets.ModalPopup');
  }
} else {
  XWiki.widgets.StepPopup = Class.create(XWiki.widgets.ModalPopup, {
    // Default parameters can be added to the custom class.
    defaultInteractionParameters : {
    },
    // Constructor. Registers the key listener that pops up the dialog.
    initialize : function($super, interactionParameters) {
      this.interactionParameters = Object.extend(Object.clone(this.defaultInteractionParameters), interactionParameters || {});
      // call constructor from ModalPopup with params content, shortcuts, options
      $super(
        this.createContent(this.interactionParameters),
        {
          'show'  : { method : this.showDialog,  keys : [] },
          'close' : { method : this.closeDialog, keys : ['Esc'] }
        },
        {
          displayCloseButton : true, 
          verticalPosition : 'top',
          backgroundColor : '#FFF'
        }
      );
      this.showDialog();
      this.setClass('my-modal-popup');
    },
    // Get the content of the modal dialog using ajax
    createContent : function (data) {
      var content =  new Element('div', {'class': 'modal-popup'});
      // get page content for the pageURL
      new Ajax.Request(data.pageURL,
      {
        method:'get',
        onSuccess: function(transport){
          var response = transport.responseText || 'no response text';
          content.insert(response);
        },
        onFailure: function() { content.insert('Something went wrong...'); 
      }
      });
      return content;
    }
  });
} // if the parent widget is defined
