// Generated by CoffeeScript 1.12.7
var CustomDataTypeHtmlEditor,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

CustomDataTypeHtmlEditor = (function(superClass) {
  extend(CustomDataTypeHtmlEditor, superClass);

  function CustomDataTypeHtmlEditor() {
    this.getQueryFieldBadge = bind(this.getQueryFieldBadge, this);
    return CustomDataTypeHtmlEditor.__super__.constructor.apply(this, arguments);
  }

  CustomDataTypeHtmlEditor.prototype.getCustomDataTypeName = function() {
    return "custom:base.custom-data-type-html-editor.html_editor";
  };

  CustomDataTypeHtmlEditor.prototype.getCustomDataTypeNameLocalized = function() {
    return $$("custom.data.type.html-editor.name");
  };

  CustomDataTypeHtmlEditor.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    return [];
  };

  CustomDataTypeHtmlEditor.prototype.renderFieldAsGroup = function() {
    return false;
  };

  CustomDataTypeHtmlEditor.prototype.supportsStandard = function() {
    return false;
  };

  CustomDataTypeHtmlEditor.prototype.supportsPrinting = function() {
    return true;
  };

  CustomDataTypeHtmlEditor.prototype.renderSearchInput = function(data, opts) {
    if (opts == null) {
      opts = {};
    }
    return new SearchToken({
      column: this,
      data: data,
      fields: opts.fields
    }).getInput().DOM;
  };

  CustomDataTypeHtmlEditor.prototype.getFieldNamesForSearch = function() {
    return this.__getFieldNames();
  };

  CustomDataTypeHtmlEditor.prototype.getFieldNamesForSuggest = function() {
    return this.__getFieldNames();
  };

  CustomDataTypeHtmlEditor.prototype.getQueryFieldBadge = function(data) {
    var badge, value;
    if (data[(this.name()) + ":unset"]) {
      value = $$("text.column.badge.without");
    } else {
      value = data[this.name()];
    }
    badge = {
      name: this.nameLocalized(),
      value: value
    };
    return badge;
  };

  CustomDataTypeHtmlEditor.prototype.getSearchFilter = function(data, key) {
    var filter, phrase, ref, str, val;
    if (key == null) {
      key = this.name();
    }
    filter = CustomDataTypeHtmlEditor.__super__.getSearchFilter.call(this, data, key);
    if (filter) {
      return filter;
    }
    if (CUI.util.isEmpty(data[key])) {
      return;
    }
    val = data[key];
    ref = Search.getPhrase(val), str = ref[0], phrase = ref[1];
    switch (data[key + ":type"]) {
      case "token":
      case "fulltext":
      case void 0:
        filter = {
          type: "match",
          mode: data[key + ":mode"],
          fields: this.getFieldNamesForSearch(),
          string: str,
          phrase: phrase
        };
        break;
      case "field":
        filter = {
          type: "in",
          fields: this.getFieldNamesForSearch(),
          "in": [str]
        };
    }
    return filter;
  };

  CustomDataTypeHtmlEditor.prototype.__getFieldNames = function() {
    var fieldNames;
    fieldNames = [(this.fullName()) + ".search_value"];
    return fieldNames;
  };

  CustomDataTypeHtmlEditor.prototype.renderEditorInput = function(data, topLevelData, opts) {
    var baseCssURL, customCSSURL, editorContent, editorToolbar, initData, inputEditor, inputElement, openEditorButton, placeholderLabel, ref, ref1, resultObject, standard;
    initData = this.__initData(data);
    resultObject = (ref = opts.editor) != null ? ref.object : void 0;
    standard = (resultObject != null ? resultObject.getStandard() : void 0) || "";
    baseCssURL = "build/webfrontend/base.css";
    customCSSURL = (ref1 = ez5.session.getBaseConfig("plugin", "custom-data-type-html-editor").html_editor) != null ? ref1.custom_css_url : void 0;
    editorToolbar = "undo redo | image | styleselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent numlist bullist";
    inputEditor = null;
    inputElement = CUI.dom.element("input");
    inputElement.value = initData.value;
    CUI.dom.addClass(inputElement, "ez5-custom-data-type-html-editor-fixed-height");
    CUI.dom.setStyle(inputElement, {
      visibility: "hidden"
    });
    CustomDataTypeHtmlEditor.loadLibraryPromise.done(function() {
      return CUI.dom.waitForDOMInsert({
        node: inputElement
      }).done(function() {
        return tinymce.init({
          menubar: false,
          toolbar: editorToolbar,
          toolbar_mode: 'sliding',
          target: inputElement,
          content_css: [baseCssURL, customCSSURL],
          plugins: "image paste lists",
          paste_data_images: true,
          setup: (function(inputText) {
            CUI.dom.setStyle(inputElement, {
              visibility: ""
            });
            inputEditor = inputText;
            return inputText.on('change', function() {
              initData.value = inputText.getContent();
              return CUI.Events.trigger({
                node: editorContent,
                type: "editor-changed"
              });
            });
          })
        });
      });
    });
    placeholderLabel = new CUI.Label({
      text: $$("custom.data.type.html-editor.editor.editing-placeholder"),
      "class": "ez5-custom-data-type-html-editor-description",
      multiline: true,
      appearance: "secondary"
    });
    CUI.dom.hideElement(placeholderLabel);
    openEditorButton = new LocaButton({
      loca_key: "custom.data.type.html-editor.editor.window.open-button",
      appearance: "link",
      size: "mini",
      onClick: (function(_this) {
        return function() {
          var ez5CSSLinkElement, features, manualClose, plugin, pluginCSSLinkElement, ref2, saveChanges, verticalLayout, win, windowInputEditor, windowInputElement;
          saveChanges = false;
          manualClose = false;
          initData._editorWindowOpen = true;
          openEditorButton.disable();
          CUI.dom.hideElement(inputEditor.getContainer());
          CUI.dom.showElement(placeholderLabel);
          features = "toolbar=no,status=no,menubar=no,scrollbars=yes,width=" + window.innerWidth + ",height=" + window.innerHeight;
          win = window.open("", "_blank", features);
          win.document.title = $$("custom.data.type.html-editor.editor.window.title", {
            standard: ez5.loca.getBestDatabaseValue(standard != null ? (ref2 = standard["1"]) != null ? ref2.text : void 0 : void 0) || "",
            fieldName: _this.ColumnSchema._name_localized
          });
          ez5CSSLinkElement = CUI.dom.element("link", {
            href: ez5.getAbsoluteURL(ez5.cssLoader.getActiveCSS().url),
            rel: "stylesheet",
            type: "text/css"
          });
          win.document.head.appendChild(ez5CSSLinkElement);
          plugin = ez5.pluginManager.getPlugin("custom-data-type-html-editor");
          pluginCSSLinkElement = CUI.dom.element("link", {
            href: ez5.getAbsoluteURL(plugin.getBareBaseURL() + plugin.getWebfrontend().css),
            rel: "stylesheet",
            type: "text/css"
          });
          win.document.head.appendChild(pluginCSSLinkElement);
          windowInputElement = CUI.dom.element("input");
          windowInputElement.value = initData.value;
          verticalLayout = new CUI.VerticalLayout({
            "class": "ez5-custom-data-type-html-editor-window",
            center: {
              content: windowInputElement
            },
            bottom: {
              content: new CUI.HorizontalLayout({
                right: {
                  content: new CUI.Buttonbar({
                    buttons: [
                      {
                        text: $$("custom.data.type.html-editor.editor.window.button.cancel"),
                        onClick: function() {
                          var confirmationChoice;
                          confirmationChoice = new CUI.ConfirmationChoice({
                            text: $$("custom.data.type.html-editor.editor.window.cancel-confirmation"),
                            title: $$("custom.data.type.html-editor.editor.window.button.cancel"),
                            choices: [
                              {
                                text: $$("base.cancel")
                              }, {
                                text: $$("base.ok"),
                                onClick: function() {
                                  manualClose = true;
                                  return win.close();
                                }
                              }
                            ]
                          });
                          confirmationChoice.open();
                          CUI.dom.append(win.document.body, confirmationChoice.getLayerRoot());
                        }
                      }, {
                        primary: true,
                        text: $$("custom.data.type.html-editor.editor.window.button.apply"),
                        onClick: function() {
                          saveChanges = true;
                          manualClose = true;
                          return win.close();
                        }
                      }
                    ]
                  })
                }
              })
            }
          });
          win.document.body.appendChild(verticalLayout.DOM);
          windowInputEditor = null;
          CustomDataTypeHtmlEditor.loadLibraryPromise.done(function() {
            return tinymce.init({
              menubar: false,
              toolbar: editorToolbar,
              target: windowInputElement,
              toolbar_mode: 'sliding',
              height: "100%",
              content_css: [baseCssURL, customCSSURL],
              plugins: "image paste lists",
              setup: (function(inputText) {
                return windowInputEditor = inputText;
              })
            });
          });
          win.addEventListener('beforeunload', function(e) {
            if (!manualClose) {
              return e.returnValue = null;
            }
          });
          return win.addEventListener('unload', function() {
            openEditorButton.enable();
            CUI.dom.hideElement(placeholderLabel);
            CUI.dom.showElement(inputEditor.getContainer());
            delete initData._editorWindowOpen;
            if (saveChanges) {
              initData.value = windowInputEditor.getContent();
              inputEditor.setContent(initData.value);
              CUI.Events.trigger({
                node: editorContent,
                type: "editor-changed"
              });
            }
          });
        };
      })(this)
    });
    editorContent = new CUI.VerticalLayout({
      top: {
        content: placeholderLabel
      },
      center: {
        content: inputElement
      },
      bottom: {
        content: openEditorButton
      }
    });
    return editorContent;
  };

  CustomDataTypeHtmlEditor.prototype.__getCustomCSSElement = function() {
    var customCssURL, linkElement, ref;
    customCssURL = (ref = ez5.session.getBaseConfig("plugin", "custom-data-type-html-editor").html_editor) != null ? ref.custom_css_url : void 0;
    if (!customCssURL) {
      return;
    }
    linkElement = CUI.dom.element("link", {
      href: customCssURL,
      rel: "stylesheet",
      type: "text/css"
    });
    return linkElement;
  };

  CustomDataTypeHtmlEditor.prototype.__getBaseCSSElement = function() {
    var baseCssURL, linkElement;
    baseCssURL = "build/webfrontend/base.css";
    if (!baseCssURL) {
      return;
    }
    linkElement = CUI.dom.element("link", {
      href: baseCssURL,
      rel: "stylesheet",
      type: "text/css"
    });
    return linkElement;
  };

  CustomDataTypeHtmlEditor.prototype.renderDetailOutput = function(data, topLevelData, opts) {
    var baseLinkElement, body, bodyContent, customLinkElement, detailContent, div, head, html, iframe, initData, openButton, ref, ref1, resultObject, standard, standardTitle;
    initData = this.__initData(data);
    bodyContent = CUI.dom.htmlToNodes(initData.value);
    if (opts.for_print) {
      div = CUI.dom.div();
      CUI.dom.append(div, bodyContent);
      return div;
    }
    iframe = CUI.dom.$element("iframe", "ez5-custom-data-type-html-editor-iframe");
    html = CUI.dom.element("html");
    head = CUI.dom.element("head");
    body = CUI.dom.element("body");
    CUI.dom.append(html, head);
    CUI.dom.append(html, body);
    CUI.dom.setStyle(body, {
      "margin": "0px"
    });
    CUI.dom.append(body, bodyContent);
    baseLinkElement = this.__getBaseCSSElement();
    if (baseLinkElement) {
      CUI.dom.append(head, baseLinkElement);
    }
    customLinkElement = this.__getCustomCSSElement();
    if (customLinkElement) {
      CUI.dom.append(head, customLinkElement);
    }
    iframe.addEventListener("load", (function(_this) {
      return function() {
        var doc, height, iframeContent;
        iframeContent = iframe.contentDocument.documentElement;
        iframeContent.innerHTML = html.innerHTML;
        doc = iframe.contentDocument || iframe.contentWindow.document;
        height = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight);
        return iframe.style.height = height + 'px';
      };
    })(this));
    resultObject = (ref = opts.detail) != null ? ref.object : void 0;
    if (!resultObject && topLevelData) {
      resultObject = new ResultObject().setData(topLevelData);
    }
    standard = resultObject != null ? resultObject.getStandard() : void 0;
    standardTitle = ez5.loca.getBestDatabaseValue(standard != null ? (ref1 = standard["1"]) != null ? ref1.text : void 0 : void 0) || "";
    openButton = new LocaButton({
      loca_key: "custom.data.type.html-editor.detail.window.open-button",
      appearance: "link",
      size: "mini",
      onClick: (function(_this) {
        return function() {
          var features, newInputElement, win;
          openButton.disable();
          features = "toolbar=no,status=no,menubar=no,scrollbars=yes,width=" + window.innerWidth + ",height=" + window.innerHeight;
          win = window.open("", "_blank", features);
          newInputElement = CUI.dom.element("input");
          newInputElement.value = initData.value;
          win.document.title = $$("custom.data.type.html-editor.detail.window.title", {
            standard: standardTitle,
            fieldName: _this.ColumnSchema._name_localized
          });
          if (baseLinkElement) {
            win.document.head.appendChild(baseLinkElement);
          }
          if (customLinkElement) {
            win.document.head.appendChild(customLinkElement);
          }
          win.document.body.innerHTML = initData.value;
          win.addEventListener('beforeunload', function() {
            return openButton.enable();
          });
        };
      })(this)
    });
    detailContent = new CUI.VerticalLayout({
      center: {
        content: iframe
      },
      bottom: {
        content: openButton
      }
    });
    return detailContent;
  };

  CustomDataTypeHtmlEditor.prototype.getTemplateValue = function(data) {
    var ref;
    return data != null ? (ref = data._template) != null ? ref[this.name()] : void 0 : void 0;
  };

  CustomDataTypeHtmlEditor.prototype.getSaveData = function(data, save_data) {
    var fieldData;
    fieldData = data[this.name()];
    if (CUI.util.isEmpty(fieldData) || CUI.util.isEmpty(fieldData.value)) {
      fieldData = this.getTemplateValue(data);
      if (CUI.util.isEmpty(fieldData)) {
        return save_data[this.name()] = null;
      }
    }
    if (fieldData._editorWindowOpen) {
      throw new InvalidSaveDataException({
        text: $$("custom.data.type.html-editor.editor.window.alert.is-open")
      });
    }
    save_data[this.name()] = CustomDataTypeHtmlEditor.buildData(fieldData.value);
    return save_data[this.name()];
  };

  CustomDataTypeHtmlEditor.buildData = function(stringContent) {
    var _, data, ref, searchValue, text, value;
    if (ez5.version("6") && CUI.util.isEmpty(stringContent)) {
      return null;
    }
    searchValue = [];
    ref = CUI.dom.htmlToNodes(stringContent);
    for (_ in ref) {
      value = ref[_];
      text = value.textContent;
      if (!text || /^(\s|\n)$/.test(text)) {
        continue;
      }
      searchValue.push(value.textContent.trim());
    }
    searchValue = searchValue.join(" ");
    data = {
      value: stringContent,
      search_value: searchValue,
      _fulltext: {
        text: searchValue
      }
    };
    return data;
  };

  CustomDataTypeHtmlEditor.prototype.__initData = function(data) {
    var initData;
    if (!data[this.name()]) {
      initData = {
        value: ""
      };
      data[this.name()] = initData;
    } else {
      initData = data[this.name()];
    }
    return initData;
  };

  CustomDataTypeHtmlEditor.prototype.isEmpty = function(data) {
    var ref;
    return CUI.util.isEmpty((ref = data[this.name()]) != null ? ref.value : void 0);
  };

  CustomDataTypeHtmlEditor.prototype.hasRenderForTable = function() {
    return false;
  };

  CustomDataTypeHtmlEditor.prototype.hasRenderForSort = function() {
    return false;
  };

  CustomDataTypeHtmlEditor.prototype.getCSVDestinationFields = function(csvImporter) {
    var opts;
    opts = {
      csvImporter: csvImporter,
      field: this
    };
    return [new CustomDataTypeHtmlEditorCSVImporterDestinationField(opts)];
  };

  return CustomDataTypeHtmlEditor;

})(CustomDataType);

CustomDataType.register(CustomDataTypeHtmlEditor);

ez5.session_ready(function() {
  var plugin, url;
  plugin = ez5.pluginManager.getPlugin("custom-data-type-html-editor");
  url = ez5.getAbsoluteURL(plugin.getBaseURL() + "/tinymce/tinymce.min.js");
  CustomDataTypeHtmlEditor.loadLibraryPromise = CUI.loadScript(url);
});
