"use strict";
/**
 * @param {string} e
 * @return {?}
 */
function _typeof(e) {
  return (_typeof =
    "function" == typeof Symbol && "symbol" == typeof Symbol.iterator
      ? function (event) {
          return typeof event;
        }
      : function (obj) {
          return obj &&
            "function" == typeof Symbol &&
            obj.constructor === Symbol &&
            obj !== Symbol.prototype
            ? "symbol"
            : typeof obj;
        })(e);
}
!(function ($, me, self) {
  var App = {
    Views: {},
    Models: {},
    Collections: {},
    Behaviors: {},
    Layout: null,
    Manager: null,
  };
  App.Models.Template = Backbone.Model.extend({
    defaults: {
      template_id: 0,
      title: "",
      type: "",
      thumbnail: "",
      url: "",
      tags: [],
      isPro: false,
    },
  });
  App.Collections.Template = Backbone.Collection.extend({
    model: App.Models.Template,
  });
  App.Behaviors.InsertTemplate = Marionette.Behavior.extend({
    ui: {
      insertButton: ".ci-elementor-template-library-insert-button",
    },
    events: {
      "click @ui.insertButton": "onInsertButtonClick",
    },
    onInsertButtonClick: function () {
      self.library.insertTemplate({
        model: this.view.model,
      });
    },
  });
  App.Views.EmptyTemplateCollection = Marionette.ItemView.extend({
    id: "elementor-template-library-templates-empty",
    template: "#ci-elementor-template-library-empty",
    ui: {
      title: ".elementor-template-library-blank-title",
      message: ".elementor-template-library-blank-message",
    },
    modesStrings: {
      empty: {
        title: "No templates found",
        message: "There are currently no available templates",
      },
      noResults: {
        title: "No templates found",
        message: "No templates found, please try refining your search",
      },
    },
    getCurrentMode: function () {
      return self.library.getFilter("text") ? "noResults" : "empty";
    },
    onRender: function () {
      var e = this.modesStrings[this.getCurrentMode()];
      this.ui.title.html(e.title);
      this.ui.message.html(e.message);
    },
  });
  App.Views.Loading = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-loading",
    id: "ci-elementor-template-library-loading",
  });
  App.Views.Logo = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-header-logo",
    className: "ci-elementor-template-library-header-logo",
    templateHelpers: function () {
      return {
        title: this.getOption("title"),
      };
    },
  });
  App.Views.BackButton = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-header-back",
    id: "elementor-template-library-header-preview-back",
    className: "ci-elementor-template-library-header-back",
    events: function () {
      return {
        click: "onClick",
      };
    },
    onClick: function () {
      self.library.showTemplatesView();
    },
  });
  App.Views.Menu = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-header-menu",
    id: "elementor-template-library-header-menu",
    className: "ci-elementor-template-library-header-menu",
    templateHelpers: function () {
      return self.library.getTabs();
    },
    ui: {
      menuItem: ".elementor-template-library-menu-item",
    },
    events: {
      "click @ui.menuItem": "onMenuItemClick",
    },
    onMenuItemClick: function (event) {
      self.library.setFilter("tags", "");
      self.library.setFilter("text", "");
      self.library.setFilter("type", event.currentTarget.dataset.tab, true);
      self.library.showTemplatesView();
    },
  });
  App.Views.ResponsiveMenu = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-header-menu-responsive",
    id: "elementor-template-library-header-menu-responsive",
    className: "ci-elementor-template-library-header-menu-responsive",
    ui: {
      items: "> .elementor-component-tab",
    },
    events: {
      "click @ui.items": "onTabItemClick",
    },
    onTabItemClick: function (obj) {
      obj = $(obj.currentTarget);
      var data = obj.data("tab");
      self.library.channels.tabs.trigger("change:device", data, obj);
    },
  });
  App.Views.Actions = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-header-actions",
    id: "elementor-template-library-header-actions",
    ui: {
      sync: "#ci-elementor-template-library-header-sync i",
    },
    events: {
      "click @ui.sync": "onSyncClick",
    },
    onSyncClick: function () {
      var $ = this;
      $.ui.sync.addClass("eicon-animation-spin");
      self.library.requestLibraryData({
        onUpdate: function () {
          $.ui.sync.removeClass("eicon-animation-spin");
          self.library.updateBlocksView();
        },
        forceUpdate: true,
        forceSync: true,
      });
    },
  });
  App.Views.InsertWrapper = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-header-insert",
    id: "elementor-template-library-header-preview",
    behaviors: {
      insertTemplate: {
        behaviorClass: App.Behaviors.InsertTemplate,
      },
    },
  });
  App.Views.Preview = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-preview",
    className: "ci-elementor-template-library-preview",
    ui: function () {
      return {
        iframe: "> iframe",
      };
    },
    onRender: function () {
      this.ui.iframe.attr("src", this.getOption("url")).hide();
      var editor = this;
      var addonView = new App.Views.Loading().render();
      this.$el.append(addonView.el);
      this.ui.iframe.on("load", function () {
        editor.$el.find("#ci-elementor-template-library-loading").remove();
        editor.ui.iframe.show();
      });
    },
  });
  App.Views.TemplateCollection = Marionette.CompositeView.extend({
    template: "#ci-elementor-template-library-templates",
    id: "ci-elementor-template-library-templates",
    className: function () {
      return (
        "ci-elementor-template-library-templates ci-elementor-template-library-templates--" +
        self.library.getFilter("type")
      );
    },
    childViewContainer: "#ci-elementor-template-library-templates-list",
    emptyView: function () {
      return new App.Views.EmptyTemplateCollection();
    },
    ui: {
      templatesWindow: ".ci-elementor-template-library-templates-window",
      textFilter: "#ci-elementor-template-library-search",
      tagsFilter: "#ci-elementor-template-library-filter-tags",
      filterBar: "#ci-elementor-template-library-toolbar-filter",
      counter: "#ci-elementor-template-library-toolbar-counter",
    },
    events: {
      "input @ui.textFilter": "onTextFilterInput",
      "click @ui.tagsFilter li": "onTagsFilterClick",
    },
    getChildView: function (name) {
      return App.Views.Template;
    },
    initialize: function () {
      this.listenTo(
        self.library.channels.templates,
        "filter:change",
        this._renderChildren
      );
    },
    filter: function (n) {
      var style = self.library.getFilterTerms();
      /** @type {boolean} */
      var $ = true;
      return (
        _.each(style, function (o, data) {
          data = self.library.getFilter(data);
          return data && o.callback
            ? ((o = o.callback.call(n, data)) || ($ = false), o)
            : void 0;
        }),
        $
      );
    },
    setMasonrySkin: function () {
      var e;
      if ("section" === self.library.getFilter("type")) {
        e = new elementorModules.utils.Masonry({
          container: this.$childViewContainer,
          items: this.$childViewContainer.children(),
        });
        this.$childViewContainer.imagesLoaded(e.run.bind(e));
      }
    },
    onRenderCollection: function () {
      this.setMasonrySkin();
      this.updatePerfectScrollbar();
      this.setTemplatesFoundText();
    },
    setTemplatesFoundText: function () {
      var key = self.library.getFilter("type");
      var l = this.children.length;
      /** @type {string} */
      var stxt3 = "<b>" + l + "</b>";
      /** @type {string} */
      stxt3 = stxt3 + ("section" === key ? " block" : " " + key);
      if (1 < l) {
        /** @type {string} */
        stxt3 = stxt3 + "s";
      }
      this.ui.counter.html((stxt3 = stxt3 + " found"));
    },
    onTextFilterInput: function () {
      var addonInstall = this;
      _.defer(function () {
        self.library.setFilter("text", addonInstall.ui.textFilter.val());
      });
    },
    onTagsFilterClick: function (e) {
      e = $(e.currentTarget);
      var value = e.data("tag");
      self.library.setFilter("tags", value);
      e.addClass("active").siblings().removeClass("active");
      value = value ? self.library.getTags()[value] : "Filter";
      this.ui.filterBar
        .find(".ci-elementor-template-library-filter-btn")
        .html(value + ' <i class="eicon-caret-down"></i>');
    },
    updatePerfectScrollbar: function () {
      if (!this.perfectScrollbar) {
        this.perfectScrollbar = new PerfectScrollbar(
          this.ui.templatesWindow[0],
          {
            suppressScrollX: true,
          }
        );
      }
      /** @type {boolean} */
      this.perfectScrollbar.isRtl = false;
      this.perfectScrollbar.update();
    },
    setTagsFilterHover: function () {
      var args = this;
      args.ui.filterBar.hoverIntent(
        function () {
          args.ui.tagsFilter.css("display", "block");
          args.ui.filterBar
            .find(".ci-elementor-template-library-filter-btn i")
            .addClass("eicon-caret-down")
            .removeClass("eicon-caret-right");
        },
        function () {
          args.ui.tagsFilter.css("display", "none");
          args.ui.filterBar
            .find(".ci-elementor-template-library-filter-btn i")
            .addClass("eicon-caret-right")
            .removeClass("eicon-caret-down");
        },
        {
          sensitivity: 50,
          interval: 150,
          timeout: 100,
        }
      );
    },
    onRender: function () {
      this.setTagsFilterHover();
      this.updatePerfectScrollbar();
    },
  });
  App.Views.Template = Marionette.ItemView.extend({
    template: "#ci-elementor-template-library-template",
    className: "ci-elementor-template-library-template",
    ui: {
      previewButton:
        ".ci-elementor-template-library-preview-button, .ci-elementor-template-library-template-preview",
    },
    events: {
      "click @ui.previewButton": "onPreviewButtonClick",
    },
    behaviors: {
      insertTemplate: {
        behaviorClass: App.Behaviors.InsertTemplate,
      },
    },
    onPreviewButtonClick: function () {
      self.library.showPreviewView(this.model);
    },
  });
  App.Modal = elementorModules.common.views.modal.Layout.extend({
    getModalOptions: function () {
      return {
        id: "ci-elementor-template-library-modal",
        hide: {
          onOutsideClick: true,
          onEscKeyPress: true,
          onBackgroundClick: true,
        },
      };
    },
    getTemplateActionButton: function (schedulingTemplate) {
      /** @type {string} */
      schedulingTemplate = "insert-button";
      schedulingTemplate = Marionette.TemplateCache.get(
        "#ci-elementor-template-library-" + schedulingTemplate
      );
      return Marionette.Renderer.render(schedulingTemplate);
    },
    showLogo: function (callback) {
      this.getHeaderView().logoArea.show(new App.Views.Logo(callback));
    },
    showDefaultHeader: function () {
      this.showLogo({
        title: "Ignition Templates",
      });
      var headerView = this.getHeaderView();
      headerView.tools.show(new App.Views.Actions());
      headerView.menuArea.show(new App.Views.Menu());
    },
    showPreviewView: function (templateModel) {
      var headerView = this.getHeaderView();
      headerView.menuArea.show(new App.Views.ResponsiveMenu());
      headerView.logoArea.show(new App.Views.BackButton());
      headerView.tools.show(
        new App.Views.InsertWrapper({
          model: templateModel,
        })
      );
      this.modalContent.show(
        new App.Views.Preview({
          url: templateModel.get("url"),
        })
      );
    },
    showTemplatesView: function (templatesCollection) {
      this.showDefaultHeader();
      this.modalContent.show(
        new App.Views.TemplateCollection({
          collection: templatesCollection,
        })
      );
    },
  });
  /**
   * @return {undefined}
   */
  App.Manager = function () {
    /**
     * @return {undefined}
     */
    function init() {
      var e = $(this).closest(".elementor-top-section");
      var beforeId = e.data("id");
      var trackers = me.documents.getCurrent().container.children;
      e = e.prev(".elementor-add-section");
      if (trackers) {
        _.each(trackers, function (pane, navigatorType) {
          if (beforeId === pane.id) {
            /** @type {string} */
            self.atIndex = navigatorType;
          }
        });
      }
      if (!e.find(".ci-elementor-template-library-insert-button").length) {
        e.find(t).before(newSig);
      }
    }
    /**
     * @param {?} params
     * @param {!Element} $trigger
     * @return {undefined}
     */
    function save(params, $trigger) {
      $trigger
        .addClass("elementor-active")
        .siblings()
        .removeClass("elementor-active");
      $trigger = defaults[params] || defaults.desktop;
      $(".ci-elementor-template-library-preview").css("width", $trigger);
    }
    /**
     * @return {undefined}
     */
    function render() {
      var _ = window.elementor.$previewContents;
      /** @type {number} */
      var chat_retry = setInterval(function () {
        var context;
        var s;
        if (
          (s = (context = _).find(t)).length &&
          !context.find(".ci-elementor-template-library-insert-button").length
        ) {
          s.before(newSig);
        }
        context.on(
          "click.onAddElement",
          ".elementor-editor-section-settings .elementor-editor-element-add",
          init
        );
        if (0 < _.find(".elementor-add-new-section").length) {
          clearInterval(chat_retry);
        }
      }, 100);
      _.on(
        "click.onAddTemplateButton",
        ".ci-elementor-template-library-insert-button",
        self.showModal.bind(self)
      );
      this.channels.tabs.on("change:device", save);
    }
    var event;
    var tags;
    var b;
    var templatesCollection;
    var buttons;
    var time;
    var self = this;
    /** @type {string} */
    var t = ".elementor-add-new-section .elementor-add-section-drag-title";
    /** @type {string} */
    var newSig =
      '<div class="elementor-add-section-area-button ci-elementor-template-library-insert-button"></div>';
    var defaults = {
      desktop: "100%",
      tab: "768px",
      mobile: "360px",
    };
    /** @type {number} */
    this.atIndex = -1;
    this.channels = {
      tabs: Backbone.Radio.channel("tabs"),
      templates: Backbone.Radio.channel("templates"),
    };
    /**
     * @return {undefined}
     */
    this.updateBlocksView = function () {
      self.setFilter("tags", "", true);
      self.setFilter("text", "", true);
      self.getModal().showTemplatesView(templatesCollection);
    };
    /**
     * @param {string} value
     * @param {string} id
     * @param {boolean} data
     * @return {undefined}
     */
    this.setFilter = function (value, id, data) {
      self.channels.templates.reply("filter:" + value, id);
      if (!data) {
        self.channels.templates.trigger("filter:change");
      }
    };
    /**
     * @param {string} id
     * @return {?}
     */
    this.getFilter = function (id) {
      return self.channels.templates.request("filter:" + id);
    };
    /**
     * @return {?}
     */
    this.getFilterTerms = function () {
      return {
        tags: {
          callback: function (t) {
            return _.any(this.get("tags"), function (e) {
              return 0 <= e.indexOf(t);
            });
          },
        },
        text: {
          callback: function (t) {
            return (
              (t = t.toLowerCase()),
              0 <= this.get("title").toLowerCase().indexOf(t) ||
                _.any(this.get("tags"), function (e) {
                  return 0 <= e.indexOf(t);
                })
            );
          },
        },
        type: {
          callback: function (type) {
            return this.get("type") === type;
          },
        },
      };
    };
    /**
     * @return {undefined}
     */
    this.showModal = function () {
      self.getModal().showModal();
      self.showTemplatesView();
    };
    /**
     * @return {undefined}
     */
    this.closeModal = function () {
      this.getModal().hideModal();
    };
    /**
     * @return {?}
     */
    this.getModal = function () {
      return (event = event || new App.Modal());
    };
    /**
     * @return {undefined}
     */
    this.init = function () {
      self.setFilter("type", "page", true);
      me.on("preview:loaded", render.bind(this));
    };
    /**
     * @return {?}
     */
    this.getTabs = function () {
      var i = this.getFilter("type");
      var result = {
        page: {
          title: "Pages",
        },
      };
      return (
        _.each(result, function (canCreateDiscussions, categoryStart) {
          if (i === categoryStart) {
            /** @type {boolean} */
            result[i].active = true;
          }
        }),
        {
          tabs: result,
        }
      );
    };
    /**
     * @return {?}
     */
    this.getTags = function () {
      return tags;
    };
    /**
     * @return {?}
     */
    this.getTypeTags = function () {
      var comparator = self.getFilter("type");
      return b[comparator];
    };
    /**
     * @return {undefined}
     */
    this.showTemplatesView = function () {
      self.setFilter("tags", "", true);
      self.setFilter("text", "", true);
      if (templatesCollection) {
        self.getModal().showTemplatesView(templatesCollection);
      } else {
        self.loadTemplates(function () {
          self.getModal().showTemplatesView(templatesCollection);
        });
      }
    };
    /**
     * @param {!Object} templateModel
     * @return {undefined}
     */
    this.showPreviewView = function (templateModel) {
      self.getModal().showPreviewView(templateModel);
    };
    /**
     * @param {!Function} callback
     * @return {undefined}
     */
    this.loadTemplates = function (callback) {
      self.requestLibraryData({
        onBeforeUpdate: self.getModal().showLoadingView.bind(self.getModal()),
        onUpdate: function () {
          self.getModal().hideLoadingView();
          if (callback) {
            callback();
          }
        },
      });
    };
    /**
     * @param {!Object} options
     * @return {undefined}
     */
    this.requestLibraryData = function (options) {
      var data;
      if (templatesCollection && !options.forceUpdate) {
        if (options.onUpdate) {
          options.onUpdate();
        }
      } else {
        if (options.onBeforeUpdate) {
          options.onBeforeUpdate();
        }
        data = {
          data: {},
          success: function (item) {
            templatesCollection = new App.Collections.Template(item.templates);
            if (item.tags) {
              tags = item.tags;
            }
            if (item.type_tags) {
              b = item.type_tags;
            }
            if (item.buttons) {
              buttons = item.buttons;
            }
            if (options.onUpdate) {
              options.onUpdate();
            }
          },
        };
        if (options.forceSync) {
          /** @type {boolean} */
          data.data.sync = true;
        }
        elementorCommon.ajax.addRequest("get_ci_library_data", data);
      }
    };
    /**
     * @param {number} options
     * @param {?} data
     * @return {undefined}
     */
    this.requestTemplateData = function (options, data) {
      options = {
        unique_id: options,
        data: {
          edit_mode: true,
          display: true,
          template_id: options,
        },
      };
      if (data) {
        jQuery.extend(true, options, data);
      }
      elementorCommon.ajax.addRequest("get_ci_template_data", options);
    };
    /**
     * @param {!Object} editor
     * @return {undefined}
     */
    this.insertTemplate = function (editor) {
      var graph = editor.model;
      var self = this;
      self.getModal().showLoadingView();
      self.requestTemplateData(graph.get("template_id"), {
        success: function (e) {
          self.getModal().hideLoadingView();
          self.getModal().hideModal();
          var t = {};
          if (-1 !== self.atIndex) {
            t.at = self.atIndex;
          }
          $e.run("document/elements/import", {
            model: graph,
            data: e,
            options: t,
          });
          /** @type {number} */
          self.atIndex = -1;
        },
        error: function (e) {
          self.showErrorDialog(e);
        },
        complete: function (isCalled) {
          self.getModal().hideLoadingView();
          window.elementor.$previewContents
            .find(".elementor-add-section .elementor-add-section-close")
            .click();
        },
      });
    };
    /**
     * @param {string} error
     * @return {undefined}
     */
    this.showErrorDialog = function (error) {
      var msg;
      if ("object" === _typeof(error)) {
        /** @type {string} */
        msg = "";
        _.each(error, function (origErr) {
          msg = msg + ("<div>" + origErr.message + ".</div>");
        });
        error = msg;
      } else {
        if (error) {
          /** @type {string} */
          error = error + ".";
        } else {
          /** @type {string} */
          error = "<i>&#60;The error message is empty&#62;</i>";
        }
      }
      self
        .getErrorDialog()
        .setMessage(
          'The following error(s) occurred while processing the request:<div id="elementor-template-library-error-info">' +
            error +
            "</div>"
        )
        .show();
    };

    this.getTemplatesCollection = function () {
      return templatesCollection;
    };

    this.getButtons = function () {
      return buttons;
    };

    /**
     * @return {?}
     */
    this.getErrorDialog = function () {
      return (time =
        time ||
        elementorCommon.dialogsManager.createWidget("alert", {
          id: "elementor-template-library-error-dialog",
          headerMessage: "An error occurred",
        }));
    };
  };
  self.library = new App.Manager();
  self.library.init();
  /** @type {!Object} */
  window.ciet = self;
})(jQuery, window.elementor, window.ciet || {});
