/**
 * This script creates the 'uberchart' TinyMCE plugin with the related 'selectuberchart' TinyMCE button, more information
 * are available in the TinyMCE documentation:
 *
 * - https://www.tinymce.com/docs/
 *
 * The modal window is handled with the windowManager API:
 *
 * - https://www.tinymce.com/docs/api/tinymce/tinymce.windowmanager/
 *
 * To have a general idea on how this script works check out the following resources:
 *
 * - https://www.tinymce.com/docs/advanced/creating-a-plugin/
 * - http://jamesdigioia.com/add-button-pop-wordpresss-tinymce-editor/
 */
(function($) {

  //Creates the 'uberchart' plugin
  tinymce.PluginManager.add('uberchart', function(editor, url) {

    //Creates the 'selectuberchart' TinyMCE button and associate the 'openuberchart' command with its click
    editor.addButton('selectuberchart',
        {title: 'UberChart', cmd: 'openuberchart', icon: 'icon dashicons-chart-line',});

    //Create the 'openuberchart' command
    editor.addCommand('openuberchart', function() {

      //Open the modal window
      editor.windowManager.open({

        //Set the various properties of the modal window
        title: 'UberChart',
        width: 300,
        height: 72,
        id: 'dauc-uberchart',

        /**
         * Add buttons in the bottom of the modal window. (eg. Add Chart, Add Shortcode, Insert, Cancel, etc.)
         *
         * The buttons should be provided as objects of this array, in this case there is only a single object/button.
         */
        buttons: [
          {
            text: 'Add Chart',
            id: 'dauc-button-add-chart',
            class: 'dauc-button'
            ,
            onclick: function(e) {
              var chartId = $('#chart-id').val();
              if (chartId === null) {
                chartId = '';
              }

              //Add the shortcode in the post
              editor.execCommand('mceInsertContent', false, '[uberchart id="' + chartId + '"]');

              //Close the modal window
              editor.windowManager.close();
            },
          }],

      });

      //Generates the content of modal window
      appendContent();

    });

  });

  /**
   * Get the modal window content with an AJAX request and append it in the modal window.
   */
  function appendContent() {

    //Get a reference to the DOM element
    var contentBody = $('#dauc-uberchart-body');

    //Prepare the parameters for the AJAX request
    var data = {
      action: 'dauc_get_modal_window_content',
      security: dauc_nonce,
    };

    //Send the AJAX request
    $.post(ajaxurl, data, function(responseHtml) {

      //Append the content in the modal window
      contentBody.append(responseHtml);

      //Initialize Chosen
      $('#chart-id').chosen();

    });

  }

})(jQuery);