(function($){"use strict";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

$(document).ready(function () {
  $('[data-type="flo_flexible_content"]').on("click", ".flo-flex-builder__open-trigger", function () {
    var popup = $(this).siblings(".flo-flex-builder__popup-wrap");
    var iframeSrc = popup.attr("src");
    /* START: Block Wordpress Areas from scrolling when entering FlexBlock */

    $(".edit-post-layout__content").css("overflow", "hidden");
    $(".edit-post-sidebar").css("overflow", "hidden");
    $("body.wp-admin").css("overflow", "hidden");

    if ($("body.auto-fold .edit-post-layout__content").length) {
      $("body.auto-fold .edit-post-layout__content").css({
        "z-index": 1000000,
        overflow: "visible"
      });
    }
    /* END: Block Wordpress Areas from scrolling when entering FlexBlock */


    popup.fadeIn("250", function () {
      popup.attr("src", popup.attr("data-src"));
      popup.addClass("flo-flex-builder__popup-active");
    });
  }); // TODO: check to target each iframe and message correctly, do not listen to ALL WINDOW IFRAME MESSAGES!!!

  var flexImageFrame;

  function flexHandleMediaUpload(iframeTarget, dataFromFlex) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    var frameTitle = "Add Image";
    var actionName = "changeImage";
    var library = {
      type: ["image"] // check if media was already initialized and if library type is the one we need (image or video)
      // if library type doesn't match, restart wp.media and set the necessary adjustments

    };

    if (flexImageFrame && flexImageFrame.options && flexImageFrame.options.library.type) {
      var libraryType = flexImageFrame.options.library.type;

      if (libraryType[0] !== options.library.type[0]) {
        flexImageFrame = null;
      }
    }

    if (options) {
      actionName = options.actionName ? options.actionName : "changeImage";
      frameTitle = options.frameTitle ? options.frameTitle : "Add Image";
      library = options.library ? options.library : {
        type: ["image"]
      };
    }

    if (flexImageFrame) {
      flexImageFrame.open();
      return;
    } // Create a new media flexImageFrame


    flexImageFrame = wp.media({
      title: frameTitle,
      button: {
        text: "Select"
      },
      library: library,
      multiple: false // Set to true to allow multiple files to be selected

    });
    $(flexImageFrame.modal.el).css("z-index", "101010100101"); // When an image is selected in the media flexImageFrame...

    flexImageFrame.on("select", function () {
      // Get media attachment details from the frame state
      var attachment = flexImageFrame.state().get("selection").first().toJSON();
      var attachmentDataToSend = {};

      if (actionName === "changeImage") {
        var alt = attachment.alt,
            url = attachment.url,
            filename = attachment.filename,
            id = attachment.id;
        attachmentDataToSend = {
          id: id,
          alt: alt,
          url: url,
          title: filename,
          fullSize: {
            w: attachment.sizes.full.width,
            h: attachment.sizes.full.height
          }
        };
        if (attachment.sizes.large) attachmentDataToSend["largeUrl"] = attachment.sizes.large.url;
        if (attachment.sizes.thumbnail) attachmentDataToSend["thumbnailUrl"] = attachment.sizes.thumbnail.url;
      } else if (actionName === "changeVideo") {
        attachmentDataToSend = {
          url: attachment.url,
          title: attachment.filename,
          length: attachment.fileLength,
          size: attachment.fileSizeHumanReadable
        };
      }

      var dataToSend = {
        fromFlex: true,
        flexData: attachmentDataToSend,
        action: actionName,
        elementID: dataFromFlex.blockID
      };
      var iframeWindow = iframeTarget.contentWindow || iframeTarget.contentDocument.parentWindow;
      iframeWindow.postMessage(dataToSend, "*");
      flexImageFrame = null;
    });
    flexImageFrame.on("open", function () {
      if (dataFromFlex.imageId) {
        var selection = flexImageFrame.state().get("selection");
        var attachment = wp.media.attachment(dataFromFlex.imageId);
        attachment.fetch();
        selection.add(attachment ? [attachment] : []);
      }
    }); // Finally, open the modal on click

    flexImageFrame.open();
  }

  function isGutenbergActive() {
    return typeof wp !== "undefined" && typeof wp.blocks !== "undefined";
  }

  function saveScreen(screenDataObj, $imgWrap) {
    var fd = new FormData();
    fd.append("main_image", screenDataObj.dataUrl);
    fd.append("screen_name", screenDataObj.blockUniqName);
    fd.append("action", "flex_upload_screen");
    return new Promise(function (resolve, reject) {
      jQuery.ajax({
        type: "POST",
        url: ajaxurl,
        data: fd,
        processData: false,
        contentType: false,
        success: function success(data, textStatus, XMLHttpRequest) {
          if (data) {
            var d = new Date();
            var src = data.replace(".png", ".png?d=".concat(d.getTime()));
            flexSetScreen($imgWrap.parents(".layout"), src);
            var srcInput = $imgWrap.parents(".layout").find(".flo-flex-builder__screenshot-url .acf-input input");
            srcInput.val(data);
            srcInput.attr("value", data);
            srcInput.trigger("change");
            resolve(data);
          }
        },
        error: function error(MLHttpRequest, textStatus, errorThrown) {
          console.error(errorThrown);
          resolve(errorThrown);
        }
      });
    });
  }

  function deleteScreen(imgUrl) {
    var fd = new FormData();
    fd.append("main_image", imgUrl);
    fd.append("action", "flex_delete_screen");
    return new Promise(function (resolve, reject) {
      jQuery.ajax({
        type: "POST",
        url: ajaxurl,
        data: fd,
        processData: false,
        contentType: false,
        success: function success(data, textStatus, XMLHttpRequest) {
          resolve(data);
        },
        error: function error(MLHttpRequest, textStatus, errorThrown) {
          console.error(errorThrown);
          resolve(errorThrown);
        }
      });
    });
  }

  function flexListener(e) {
    if (_typeof(e.data) === "object" && "fromFlex" in e.data) {
      var data = e.data;
      var iframeTarget = [].slice.call(document.querySelectorAll(".flo-flex-builder__popup-wrap")).filter(function (iframe) {
        return iframe.contentWindow === e.source;
      })[0];
      var iframeWindow = iframeTarget.contentWindow || iframeTarget.contentDocument.parentWindow;
      var dataToSend;

      switch (data.action) {
        case "iframeReady":
          // flex block data
          var flexDataEnc = $(iframeTarget).siblings(".flo-flex-builder__data-holder").val();
          var flexData;

          if (flexDataEnc.length) {
            // populated block, pull existing data
            flexData = JSON.parse(flexDataEnc);
          } else {
            // new block, send just theme data
            flexData = {
              globalOptions: {}
            };
          } // THEME TYPOGRAPHY


          if (flothemes_font_map) {
            if (typeof flothemes_font_map === "string") {
              flothemes_font_map = JSON.parse(flothemes_font_map);
            }

            flexData.globalOptions.themeFonts = flothemes_font_map; // google fonts

            if (flothemes_font_map.themeGFontsURL && flothemes_font_map.themeGFontsURL.length) {
              flexData.globalOptions.themeFonts["themeGFontsURL"] = flothemes_font_map.themeGFontsURL;
            } // google fonts

          }

          if (typeof firebase_user_id !== "undefined") {
            flexData.globalOptions.firebaseID = firebase_user_id;
          } // data localized from PHP


          if (typeof flex_stylekit_color_list !== "undefined") {
            flexData.globalOptions.themeColors = flex_stylekit_color_list;
          } // get and send theme font size


          var htmlFontSizeToSend = $(iframeTarget).siblings(".flo-flex-html-font-size-val").val();
          htmlFontSizeToSend = parseFloat(htmlFontSizeToSend);
          var currentThemeFontSize = flexData.globalOptions.htmlFontSize;

          if (typeof currentThemeFontSize === "undefined" || typeof currentThemeFontSize !== "undefined" && currentThemeFontSize !== htmlFontSizeToSend) {
            flexData.globalOptions.htmlFontSize = htmlFontSizeToSend;
          } // get and send block paddings


          var blockPaddingToSend = $(iframeTarget).siblings(".flo-flex-block-padding-val").val();
          blockPaddingToSend = parseFloat(blockPaddingToSend);
          var currentBlockPadding = flexData.globalOptions.htmlPaddingsSize;

          if (typeof currentBlockPadding === "undefined" || typeof currentBlockPadding !== "undefined" && currentBlockPadding !== blockPaddingToSend) {
            flexData.globalOptions.htmlPaddingsSize = blockPaddingToSend;
          }

          var blockName = $(iframeTarget).parents(".acf-fields").first().find(".flo-flex-builder__block-name .acf-input input").val();
          flexData.globalOptions.blockName = blockName;
          dataToSend = {
            fromFlex: true,
            action: "pullData",
            flexData: flexData
          };
          iframeWindow.postMessage(dataToSend, "*");
          break;

        case "saveData":
          var requestConfig;
          var dataHolder = $(iframeTarget).siblings("textarea").get(0);
          var flexDataDec = e.data.flexData;
          flexDataDec.globalOptions.visualHelpers.grid.enable = false;
          deleteProps(flexDataDec, ["absAlign", "active_element", "editing_element", "mobile_active_element", "mobile_editing_element", "multiSelect", "multiSelectToggled", "active_group"]);
          deleteProps(flexDataDec.globalOptions, ["guides_mode", "smartGuides", "referenceElement", "elementsWithBoundingBoxes", "currentEditorViewport", "showLayers", "colorRecognizerOpen", "showRotate", "themeFonts", "themeColors", "firebaseID", "htmlFontSize", "htmlPaddingsSize"]);

          if (window.location.origin.includes("localhost")) {
            var _data = flexDataDec;
            console.log("Saving Flex Data: ", {
              data: _data
            });
          }

          var flexDataStr = JSON.stringify(flexDataDec);
          dataHolder.innerHTML = flexDataStr;
          dataHolder.value = flexDataStr;

          var saveData = function saveData() {
            var newBlockName = e.data.blockName ? e.data.blockName : null;
            var nameInput = $(iframeTarget).parents(".acf-fields").first().find(".flo-flex-builder__block-name .acf-input input");
            var currentBlockName = nameInput.val();

            if (newBlockName && newBlockName !== currentBlockName) {
              nameInput.val(newBlockName);
              nameInput.attr("value", newBlockName);
              nameInput.trigger("input");
            }

            var previewLink = false;

            if ($("#wp-admin-bar-view a").length) {
              previewLink = $("#wp-admin-bar-view a").attr("href");
            } else if ($("#edit-slug-box #sample-permalink a").length) {
              previewLink = $("#edit-slug-box #sample-permalink a").attr("href");
            } else if ($(".edit-post-post-link__link").length) {
              previewLink = $(".edit-post-post-link__link").attr("href");
            }

            if (isGutenbergActive()) {
              var wpNonceForm = jQuery(".metabox-base-form")[0];
              var floBuilderForm = jQuery(".metabox-location-normal")[0];
              var wpNonceFormData = new FormData(wpNonceForm);
              var floBuilderFormData = new FormData(floBuilderForm);
              var _iteratorNormalCompletion = true;
              var _didIteratorError = false;
              var _iteratorError = undefined;

              try {
                for (var _iterator = floBuilderFormData.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                  var pair = _step.value;
                  wpNonceFormData.append(pair[0], pair[1]);
                }
              } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion && _iterator["return"] != null) {
                    _iterator["return"]();
                  }
                } finally {
                  if (_didIteratorError) {
                    throw _iteratorError;
                  }
                }
              }

              requestConfig = {
                type: "POST",
                url: _wpMetaBoxUrl,
                dataType: "json",
                processData: false,
                contentType: false,
                data: wpNonceFormData
              };
            } else {
              requestConfig = {
                type: "post",
                url: $("#post").attr("action"),
                data: $("#post").serialize()
              };
            }

            $.ajax(_objectSpread({}, requestConfig, {
              beforeSend: function beforeSend(data) {
                dataToSend = {
                  fromFlex: true,
                  action: "savingOptions",
                  message: "Saving"
                };
                iframeWindow.postMessage(dataToSend, "*");
              },
              success: function success(data) {
                dataToSend = {
                  fromFlex: true,
                  action: "successSaving",
                  message: "Saved!",
                  previewLink: previewLink
                };
                iframeWindow.postMessage(dataToSend, "*");
              },
              error: function error(data) {
                if (data.status == 200) {
                  dataToSend = {
                    fromFlex: true,
                    action: "successSaving",
                    message: "Saved!",
                    previewLink: previewLink
                  };
                  iframeWindow.postMessage(dataToSend, "*");
                } else {
                  dataToSend = {
                    fromFlex: true,
                    action: "errorOnSaving",
                    message: "Error!"
                  };
                  iframeWindow.postMessage(dataToSend, "*"); // TODO: provide button to download backup, or attempt to save to local storage
                }
              }
            }));
          };

          var $screenField = $(iframeTarget).parents(".acf-fields").first().find(".flo-flex-builder__block-overview");

          if (e.data.screenData) {
            $screenField.find(".flo-flex-builder__see-screenshot").removeClass("flo-flex-builder__hidden");
            saveScreen(e.data.screenData, $screenField).then(function (resp) {
              saveData();
            });
          } else {
            var srcInput = $screenField.parents(".layout").find(".flo-flex-builder__screenshot-url .acf-input input");

            if (srcInput.val().length) {
              flexUnsetScreen($(iframeTarget).parents(".layout"));
              deleteScreen(srcInput.val()).then(function (res) {
                srcInput.val("");
                srcInput.attr("value", "");
                srcInput.trigger("input");
                saveData();
              });
            } else {
              saveData();
            }
          }

          break;

        case "closeFlex":
          $(iframeTarget).fadeOut("250", function () {
            $(iframeTarget).removeClass("flo-flex-builder__popup-active");
            $(iframeTarget).attr("src", "");

            if ($("body.auto-fold .edit-post-layout__content").length) {
              $("body.auto-fold .edit-post-layout__content").css({
                "z-index": "",
                overflow: ""
              });
            } // reset media library upon quiting popup


            if (flexImageFrame) flexImageFrame = null;
          });
          $(".edit-post-layout__content").css("overflow", "");
          $(".edit-post-sidebar").css("overflow", "");
          $("body.wp-admin").css("overflow", "");
          break;

        case "changeImage":
          flexHandleMediaUpload(iframeTarget, data, {
            library: {
              type: ["image"]
            },
            frameTitle: "Add Image",
            actionName: "changeImage"
          });
          break;

        case "changeVideoFile":
          flexHandleMediaUpload(iframeTarget, data, {
            library: {
              type: ["video"]
            },
            frameTitle: "Add Video",
            actionName: "changeVideo"
          });
          break;

        default:
          return;
      }
    }
  }

  window.addEventListener("message", flexListener);
  $("body").on("click", ".flo-flex-builder__export-json-trigger", function (e) {
    var dataHolder = $(e.target).parent().siblings(".flo-flex-builder__data-holder");

    if (dataHolder.val().length) {
      var data = dataHolder.val(); // check data if it contains all necessary stuff

      var decodedData = JSON.parse(data);

      if (_typeof(decodedData) === "object" && "globalOptions" in decodedData && "elements" in decodedData) {
        var fileName;

        if (decodedData.globalOptions.blockName) {
          fileName = "".concat(decodedData.globalOptions.blockName, ".json");
        } else {
          var date = new Date();
          var timestamp = date.getTime();
          fileName = "flex-export--".concat(timestamp, ".json");
        }

        var $infoMessage = $(e.target).siblings(".flo-flex-builder__info-area");
        var fileType = "application/json"; // format json value to be a bit readable

        var encodedData = JSON.stringify(decodedData, null, 2);
        var flexDataBlob = new Blob([encodedData], {
          type: fileType
        });
        var a = document.createElement("a");
        a.download = fileName;
        a.href = URL.createObjectURL(flexDataBlob);
        a.dataset.downloadurl = [fileType, a.download, a.href].join(":");
        a.style.display = "none";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        setTimeout(function () {
          URL.revokeObjectURL(a.href);
        }, 1500);
        $infoMessage.css("color", "green");
        $infoMessage.text("export successful!");
        setTimeout(function () {
          $infoMessage.text("UPLOAD YOUR BLOCK FILE");
          $infoMessage.css("color", "");
        }, 5000);
      }
    }
  });
  $("body").on("click", ".flo-flex-builder__import-json-trigger", function (e) {
    $(e.target).siblings(".flo-flex-builder__import-file").trigger("click");
  });
  var $flexBlocks = $(".acf-flexible-content .layout[data-layout='flo_flex_builder_block']");
  $flexBlocks.each(function (i, flexBlock) {
    var $fb = $(flexBlock);
    var $titleInput = $fb.find(".flo-flex-builder__block-name .acf-input-wrap input");

    if ($titleInput.length) {
      var name = $titleInput.val();
      var nameHolder = $fb.find(".acf-fc-layout-handle");
      flexSetAcfLabel(nameHolder, name);
    }

    var screenSrc = $fb.find(".flo-flex-builder__screenshot-url input").val();

    if (screenSrc) {
      flexSetScreen($fb, screenSrc);
      $fb.find(".flo-flex-builder__see-screenshot").removeClass("flo-flex-builder__hidden");
    }
  });
  var renamers = ".flo-flex-builder__custom-label";
  $("body").on("input", renamers, function (e) {
    var input = $(e.target).parents(".layout").find(".flo-flex-builder__block-name input");
    input.val($(e.target).text());
  });
  var hiddenRenamers = ".flo-flex-builder__block-name input";
  $("body").on("input", hiddenRenamers, function (e) {
    var $layout = $(e.target).parents(".layout");
    var label = $(e.target).val();
    var input = $layout.find(".flo-flex-builder__custom-label");

    if (input.length) {
      input.html($(e.target).val());
    } else {
      var nameHolder = $layout.find(".acf-fc-layout-handle");
      flexSetAcfLabel(nameHolder, label);
    }
  });
  var blockLabels = '.acf-flexible-content .layout:not(.-collapsed)[data-layout="flo_flex_builder_block"] .acf-fc-layout-handle';
  $("body").on("click", blockLabels, function (e) {
    // if block label is clicked, do your magic
    if ($(e.target).hasClass("flo-flex-builder__custom-label")) {
      e.preventDefault();
      e.stopPropagation();
      e.target.focus();
    }
  });
  $("body").on("keydown", blockLabels, function (e) {
    if (e.key === "Enter" || e.key === "Escape") {
      e.preventDefault();
      e.target.blur();
    }
  });
  $("body").on("focus", blockLabels, function (e) {
    window.getSelection().selectAllChildren(e.target);
  });
});

window.flexHandleImport = function (inputObj) {
  var files = inputObj.files;
  var $fb = $(inputObj).parents(".layout");
  var $infoMessage = $fb.find(".flo-flex-builder__info-area");

  if (files.length) {
    var file = files[0];

    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");

      reader.onload = function (e) {
        var dataHolder = $(inputObj).parent().siblings(".flo-flex-builder__data-holder"); // perform check on string and see if it is compatible object

        if (e.target.result.length) {
          try {
            var importDataString = e.target.result;
            var decodedImportData = JSON.parse(importDataString);

            if (_typeof(decodedImportData) === "object" && "globalOptions" in decodedImportData && "elements" in decodedImportData) {
              var name = decodedImportData.globalOptions.blockName;
              var nameHolder = $fb.find(".acf-fc-layout-handle");
              flexSetAcfLabel(nameHolder, name);
              $fb.find(".flo-flex-builder__block-name .acf-input input").val(name);
              var newBlockID = Math.floor(Math.random() * 90000) + 10000;
              decodedImportData.blockID = "blockID--" + newBlockID;
              importDataString = JSON.stringify(decodedImportData);
              dataHolder.val(importDataString);
              $infoMessage.css("color", "green");
              $infoMessage.text("import successful!");
              setTimeout(function () {
                $infoMessage.text("UPLOAD YOUR BLOCK FILE");
                $infoMessage.css("color", "");
                inputObj.value = "";
              }, 5000);
            } else {
              console.error("invalid import data");
            }
          } catch (err) {
            console.error(err);
            $infoMessage.text("ERROR");
            inputObj.value = "";
          }
        }
      };

      reader.onerror = function (e) {
        console.error("error reading file");
      };
    }
  }
};

var deleteProps = function deleteProps(obj, prop) {
  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (var _iterator2 = prop[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
      var p = _step2.value;
      p in obj && delete obj[p];
    }
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
        _iterator2["return"]();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }
};

var flexSetScreen = function flexSetScreen($fb, img) {
  // preview image (block is closed)
  var previewImg = $fb.find(".acf-fc-layout-preview-image");

  if (!previewImg.attr("data-orig")) {
    var origPreviewSrc = previewImg.attr("src");
    previewImg.attr("data-orig", origPreviewSrc);
  }

  previewImg.addClass("preview-screen");
  previewImg.attr("src", img); // overview img (open block)

  var overviewImg = $fb.find(".flo-flex-builder__screenshot-img-tag");

  if (!overviewImg.attr("data-orig")) {
    var origOverviewSrc = overviewImg.attr("src");
    overviewImg.attr("data-orig", origOverviewSrc);
  }

  overviewImg.attr("src", img);
  overviewImg.parents(".flo-flex-builder__custom-image-wrap").addClass("screen-visible");
};

var flexUnsetScreen = function flexUnsetScreen($fb) {
  var previewImg = $fb.find(".acf-fc-layout-preview-image");
  previewImg.attr("src", previewImg.attr("data-orig"));
  previewImg.removeClass("preview-screen"); // overview img (open block)

  var overviewImg = $fb.find(".flo-flex-builder__screenshot-img-tag");
  overviewImg.attr("src", overviewImg.attr("data-orig"));
  overviewImg.parents(".flo-flex-builder__custom-image-wrap").removeClass("screen-visible");
};

var flexSetAcfLabel = function flexSetAcfLabel(labelWrap, labelString) {
  if (labelWrap.find(".flo-flex-builder__custom-label").length) {
    labelWrap.find(".flo-flex-builder__custom-label").text(labelString);
  } else {
    var node = labelWrap.get(0);
    node.innerHTML = node.innerHTML.replace("Flex Block", "<div spellcheck=\"false\" contenteditable=\"true\" class=\"flo-flex-builder__custom-label\">".concat(labelString, "</div>"));
  }
};})(jQuery);