/**
 *  Initialize animations modal using tingle js
 */
var animationsModal = (function($) {

  var pub              = {}; // public facing functions
  var toggleAnimations = $('[data-toggle-animations]');

  /**
   * Initialize modal functionality
   */
  pub.init = function() {
    if (toggleAnimations.length > 0) {
      pub._listenForActions();
    }
  };

  /**
   * Listen for toggle buttons and call modal when clicked
   */
  pub._listenForActions = function() {
    toggleAnimations.on('click', function(e) {
      e.preventDefault();

      var toggle = $(this).attr('data-toggle-animations');

      // call our modal
      pub._animationsToggleModal(toggle);

      return false;
    })
  };

  pub._animationsToggleModal = function(toggle) {
    // instantiate new modal
    var animationsModal = new tingle.modal({
      footer: true,
      cssClass: ['animations__modal'],
      onClose: function() {
        animationsModal.destroy();
      }
    });

    var headline = ('on' === toggle ? 'Enable' : 'Disable') + ' All Modules';
    var content  = '<strong>Notice:</strong> This will turn ' + toggle + ' animations on all modules across the site.';

    if ('default' === toggle) {
      headline = 'Reset Animation Defaults';
      content  = '<strong>Notice:</strong> Selecting this option will revert all modules animations to their default state. Do you wish to continue?';
    }

    // set content
    animationsModal.setContent(
      '<h1>' + headline + '</h1>' + content
    );

    animationsModal.addFooterBtn('Continue', 'tingle-btn tingle-btn--primary tingle-btn--pull-right', function() {
      pub._toggleGlobalAnimations(toggle, animationsModal);
      $(animationsModal.modalBox).append('<div class="tingle-modal-box--loading"></div>');
    });

    // set our footer actions
    animationsModal.addFooterBtn('Cancel', 'tingle-btn tingle-btn--pull-right', function() {
      animationsModal.close();
    });

    // open the modal
    animationsModal.open();
    $('.tingle-btn--primary').focus();
  };

  pub._toggleGlobalAnimations = function(toggle, animationsModal) {
    // query external posts
    $.ajax({
      url: adminData.root + 'reach/v1/animations',
      method: 'POST',
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-WP-Nonce', adminData.nonce);
      },
      data: {
        toggle: toggle
      },
      error: function(jqXHR, textStatus, errorThrown) {
        if (errorThrown.length > 0) {
          console.log('Error toggling module animations, please try again.');
        }
      }
    }).done(function(response) {
      if (!response.length > 0) {
        return false;
      }

      animationsModal.close();
    });
  };

  return pub;

})(jQuery);