/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 175);
/******/ })
/************************************************************************/
/******/ ({

/***/ 175:
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_Core_embed_controller__ = __webpack_require__(176);


window.EmbedController = __WEBPACK_IMPORTED_MODULE_0_Core_embed_controller__["a" /* default */];

/***/ }),

/***/ 176:
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__api__ = __webpack_require__(177);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_pyrsmk_toast__ = __webpack_require__(178);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_pyrsmk_toast___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_pyrsmk_toast__);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Widget = void 0,
    Composition = void 0,
    Content = void 0,
    Skin = void 0;



var send = function send(message) {
  (window.opener || window.parent).postMessage(JSON.stringify(message), '*');
};

var messenger = {
  load: function load() {
    return send({ t: 'u', d: window.name });
  },
  apiReady: function apiReady() {
    return send({ t: 'd', d: window.name });
  },
  notify: function notify(ev, data) {
    return send({ t: 'ce', id: window.name, d: data, e: ev.type || ev });
  },
  replyPublicApiCall: function replyPublicApiCall(id, err, data) {
    return send({ t: 'pr', id: id, err: err, d: data });
  }
};

var _newComposition = function _newComposition(widget, demo) {
  var id = 'c-0';
  return {
    id: id,
    widget_id: widget.id,
    width: widget.width,
    height: widget.height,
    skin_id: widget.skins[0].id,
    content: !demo ? [] : widget.content[0].content.map(function (c, i) {
      c.id = i;
      c.composition_id = id;
      c._isDemoContent = true;
      return c;
    }),
    metadata: {
      client: (window.location.search.match(/client_id=([^\&$]+)/) || [])[1]
    }
  };
};

// TODO relay mouse and keyboard events - maybe not?

var EmbedController = function () {
  function EmbedController(el, _ref) {
    var loader = _ref.loader,
        widget = _ref.widget,
        user = _ref.user,
        composition = _ref.composition,
        skin = _ref.skin,
        js = _ref.js,
        css = _ref.css,
        data = _ref.data,
        _ref$demo = _ref.demo,
        demo = _ref$demo === undefined ? true : _ref$demo,
        _ref$bootstrapped = _ref.bootstrapped,
        bootstrapped = _ref$bootstrapped === undefined ? false : _ref$bootstrapped;

    _classCallCheck(this, EmbedController);

    this.el = el;

    this.loader = loader;

    this.bootstrapped = bootstrapped;

    if (!widget && !data) throw new Error('You must supply either `widget` or `data`');
    this.widget = widget;
    this.dataURL = data;
    this.user = user;
    this.composition = composition;
    this.skin = skin;
    this.loadDemo = demo;

    this.js = 'https://widgetic.com' + js;
    this.css = 'https://widgetic.com' + css;

    this.dataLoaded = Widgetic.Aye.defer();
    this.dataLoaded.promise.then(this._showBranding.bind(this));
    this._init();
    this._initEditorApi();
  }

  _createClass(EmbedController, [{
    key: '_init',
    value: function _init() {
      var _this = this;

      var wait = function wait() {};
      if (!this.bootstrapped) {
        __WEBPACK_IMPORTED_MODULE_1_pyrsmk_toast___default.a(
        // load shims, css and libraries in paralel
        'https://files.widgetic.com/file/widgetic-uploads/assets/js/core-js.shim.min.js', 'https://widgetic.com/bundles/blogvioapp/js/editor/core.vendor.js', 'https://widgetic.com/bundles/blogvioapp/js/require.js', 'https://widgetic.com/bundles/blogvioapp/css/embed.css', this.css, wait,
        // load spine next, depends on require.js
        'https://widgetic.com/bundles/blogvioapp/js/spine.js', wait,
        // load widgetic code, depends on spine
        'https://widgetic.com/bundles/blogvioapp/js/editor/core.js', this._loadModels.bind(this), this._loadData.bind(this), this.js,
        // load the widget, depends on hydrated models
        function () {
          return _this.dataLoaded.promise.then(_this._loadWidget.bind(_this)).fail(function (e) {
            return console.error(e);
          });
        });
      } else {
        this._loadModels();
        this._loadData();
        this._loadWidget();
      }
    }
  }, {
    key: '_loadModels',
    value: function _loadModels() {
      Widget = window.require('core/models/widget');
      Composition = window.require('core/models/composition');
      Content = window.require('core/models/content');
      Skin = window.require('core/models/skin');
    }
  }, {
    key: '_loadData',
    value: function _loadData() {
      var _this2 = this;

      // if the data is local, proceed to hydrating the models
      if (!this.dataURL) return this._hydrateModels();

      Widgetic.uxhr(this.dataURL, null, {
        success: function success(response) {
          var data = void 0;
          try {
            data = JSON.parse(response);
          } catch (e) {
            return console.error('Could not parse response', response);
          }
          _this2.skin = data.skin;
          _this2.composition = data.composition;
          _this2.widget = data.widget;
          _this2.user = data.user;
          _this2._hydrateModels();
        },
        error: function error(_error) {
          return console.error('The widget data could not be loaded', _error);
        }
      });
    }
  }, {
    key: '_hydrateModels',
    value: function _hydrateModels() {
      this.composition = this.composition || _newComposition(this.widget, this.loadDemo);
      Widget.refresh(this.widget);
      Composition.refresh(this.composition);
      Skin.refresh(this.skin || this.widget.skins);
      this._skin = Skin.first();
      Content.refresh(this.composition.content);
      this.dataLoaded.resolve();

      this._initApi();
    }
  }, {
    key: '_initApi',
    value: function _initApi() {
      var api = new __WEBPACK_IMPORTED_MODULE_0__api__["a" /* default */]();
      Widgetic.Event.on(window, 'message', api.receiver);

      api.skinSet.listen(this._onSkinSet.bind(this));
      api.contentCleared.listen(this._onContentCleared.bind(this));
      api.contentAdded.listen(this._onContentAdded.bind(this));
      api.publicApiCalled.listen(this._onPublicApiCalled.bind(this));

      messenger.apiReady();
    }
  }, {
    key: '_initEditorApi',
    value: function _initEditorApi() {
      var _this3 = this;

      window.getPreview = function () {
        return {
          widget: function widget() {
            return _this3.widgetController;
          },
          window: window
        };
      };

      window.getData = function () {
        return {
          widget: _this3.widget,
          composition: $.extend({}, _this3.composition, {
            widget_id: _this3.widget.id,
            width: (_this3.composition || _this3.widget).width,
            height: (_this3.composition || _this3.widget).height,
            content: _this3.composition.content,
            skin_id: _this3.composition.skin_id
          }),
          skin: _this3.skin || _this3.widget.skins[0],
          user: _this3.user
        };
      };

      // used by weebly editor
      // TODO remove
      // @deprecated
      window.getCurrentData = function () {
        return { widget: _this3.widgetController };
      };

      // used by weebly editor
      // TODO remove
      var access_token = (window.location.search.match(/access_token=([^\&$]+)/) || [])[1];
      if (access_token) Widgetic.auth.token(access_token);
    }
  }, {
    key: '_loadWidget',
    value: function _loadWidget() {
      var _this4 = this;

      var uri = Widgetic.parse(window.location.href);
      var mode = uri.queryKey.edit_mode !== undefined ? Widgetic.UI.Composition.EDIT_MODE : Widgetic.UI.Composition.EMBED_MODE;
      var metadata = {
        mode: mode,
        embedOptions: {
          resize: uri.queryKey.resize,
          autoscale: uri.queryKey.autoscale,
          adaptive: uri.queryKey.adaptive
        },
        widget: this.widget,
        composition: {
          id: this.composition.id
        },
        referrer: document.referrer
      };

      var _widget = window.require(this.widget.module);
      // console.log("Embed controller load:", _widget)

      this.widgetController = new _widget({ metadata: metadata }, this._skin, Content.all());
      // console.log("Embed controller load:", this.widgetController)

      this.loader && this.loader.parentNode.removeChild(this.loader);

      // TODO replace jquery use with native DOM
      var widgetContainer = $('<div class="widget-container" style="width:1px; min-width: 100%; height: 100%">');
      $(this.el).append(widgetContainer);
      // TODO remove when all widgets are updated to svelte
      widgetContainer.append(this.widgetController.el);
      this.widgetController.added();
      this.widgetController.getPublicEvents && this.widgetController.getPublicEvents().forEach(function (event) {
        _this4.widgetController.on(event, function (data) {
          return messenger.notify(event, data);
        });
      });

      messenger.load();
    }
  }, {
    key: '_showBranding',
    value: function _showBranding() {
      if (!this.user.premium || window.location.search.indexOf('branding') >= 0) {
        window.initBranding();
      }
    }
  }, {
    key: '_onSkinSet',
    value: function _onSkinSet(skin) {
      this._skin = skin;
      if (!this.widgetController) return;
      this.widgetController.setSkin(this._skin);
    }
  }, {
    key: '_onContentCleared',
    value: function _onContentCleared() {
      if (!this.widgetController) return;
      this.widgetController.clearContent();
    }
  }, {
    key: '_onContentAdded',
    value: function _onContentAdded(item) {
      if (!this.widgetController) return;
      this.widgetController.addContent(item);
    }
  }, {
    key: '_onPublicApiCalled',
    value: function _onPublicApiCalled(data) {
      if (!this.widgetController) throw new Error('The widget is not ready yet.');
      if (!this.widgetController.getPublicMethods) throw new Error('The widget does not support public api calls.');

      var publicMethods = this.widgetController.getPublicMethods();
      var widget = this.widgetController.widget;

      if (publicMethods.indexOf(data.method) === -1 || !(data.method in widget)) throw new Error('The widget does not support method `' + data.method + '`.');

      try {
        var result = widget[data.method].apply(widget, data.args);
        messenger.replyPublicApiCall(data.id, null, result);
      } catch (e) {
        messenger.replyPublicApiCall(data.id, {
          message: e.message,
          stack: e.stack
        });
      }
    }
  }]);

  return EmbedController;
}();

/* harmony default export */ __webpack_exports__["a"] = (EmbedController);

/***/ }),

/***/ 177:
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_geval_event__ = __webpack_require__(56);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_geval_event___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_geval_event__);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }



var Skin = void 0;
var Composition = void 0;
var Content = void 0;

var EmbedApi = function () {
  function EmbedApi() {
    _classCallCheck(this, EmbedApi);

    Skin = window.require('core/models/skin');
    Content = window.require('core/models/content');
    Composition = window.require('core/models/composition');

    this.eventMap = {
      cx: 'clearContent',
      sc: 'setContent',
      ac: 'addContent',
      cc: 'changeContent',
      rc: 'removeContent',
      ss: 'setSkin',
      cs: 'changeSkin',
      asht: 'addSheet',
      acss: 'addCss',
      pa: 'publicApi'
    };
    this.receiver = this.receiver.bind(this);

    this.skin = Skin.first();
    this.composition = Composition.first();

    this.skinSet = new __WEBPACK_IMPORTED_MODULE_0_geval_event___default.a();
    this.contentCleared = new __WEBPACK_IMPORTED_MODULE_0_geval_event___default.a();
    this.contentAdded = new __WEBPACK_IMPORTED_MODULE_0_geval_event___default.a();
    this.publicApiCalled = new __WEBPACK_IMPORTED_MODULE_0_geval_event___default.a();
  }

  _createClass(EmbedApi, [{
    key: 'receiver',
    value: function receiver(event) {
      var data = void 0;
      try {
        data = JSON.parse(event.data);
      } catch (e) {
        return console.warn(e);
      }
      var handler = this.eventMap[data.t];

      if (!handler || !this[handler]) return;

      try {
        this[handler](data.d);
      } catch (e) {
        console.error(e);
      }
    }

    /**
     * Replaces the current skin with the provided one.
     * TODO load defaults for missing props
     */

  }, {
    key: 'setSkin',
    value: function setSkin(newSkin) {
      this.skin.unbind();
      this.skin = new Skin(newSkin);

      this.composition.updateAttribute('skin_id', this.skin.id, { ajax: false });
      this.skinSet.broadcast(this.skin);
    }
  }, {
    key: 'changeSkin',
    value: function changeSkin(skin) {
      // console.log('Embed changeSkin:', skin);
      this.skin.updateAttributes(skin, { attribute: Object.keys(skin)[0], ajax: false });
    }
  }, {
    key: 'clearDemoContent',
    value: function clearDemoContent() {
      return Content.select(function (c) {
        return c._isDemoContent;
      }).forEach(function (c) {
        try {
          c.destroy();
        } catch (error) {}
      });
    }
  }, {
    key: 'clearContent',
    value: function clearContent() {
      Content.destroyAll();
      this.composition.updateAttribute('content', [], { ajax: false });
      this.contentCleared.broadcast();
    }
  }, {
    key: 'getContent',
    value: function getContent() {
      return this.composition.getContent();
    }
  }, {
    key: 'setContent',
    value: function setContent(data) {
      this.clearContent();
      data.map(this.addContent.bind(this));
    }

    // TODO validate limits

  }, {
    key: 'addContent',
    value: function addContent(content) {
      this.clearDemoContent();

      // return if thre's already added a content with the same id
      try {
        Content.find(content.id);
        return console.warn('Content with id ' + content.id + ' already exists, use changeContent if you want to update it!');
      } catch (error) {}

      if (content.id == null) {
        content.id = Widgetic.GUID();
      }

      if (!content.composition_id) {
        content.composition_id = this.composition.id;
      }
      var c = new Content(content);
      c.save();
      this.contentAdded.broadcast(c);
    }
  }, {
    key: 'changeContent',
    value: function changeContent(content) {
      var item = content.item ? content.item : content;
      var attribute = content.attribute;
      // console.log('Embed change content item:', item, attribute);

      // check if item has id 
      if (item.id == null) {
        return console.error('Content must have an id:', content);
      }

      // find the item to be changed
      var c = void 0;
      try {
        c = Content.find(item.id);
      } catch (error) {
        return console.warn('Content with id ' + item.id + ' doesn\'t exists, use addContent if you want to add it!');
      }

      // update the item
      c.updateAttributes(item, { attribute: attribute, ajax: false });
    }
  }, {
    key: 'removeContent',
    value: function removeContent(content) {
      try {
        return Content.find(content.id).destroy();
      } catch (e) {
        return console.error('Content ' + content.id + ' couldn\'t be removed!', e.stack);
      }
    }
  }, {
    key: 'addSheet',
    value: function addSheet(href) {
      var link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = href;

      document.head.appendChild(link);
    }
  }, {
    key: 'addCss',
    value: function addCss(css) {
      if (!this._customCssNode) {
        this._customCssNode = document.createElement('style');
        document.head.appendChild(this._customCssNode);
      }

      this._customCssNode.textContent += css;
    }
  }, {
    key: 'publicApi',
    value: function publicApi(data) {
      this.publicApiCalled.broadcast(data);
    }
  }]);

  return EmbedApi;
}();

/* harmony default export */ __webpack_exports__["a"] = (EmbedApi);

/***/ }),

/***/ 178:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(root, factory) {
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
    	return (root.toast = factory());
    }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.toast = factory();
  }
}(this, function() {
var handled_resources = {};

function Toast() {
	var head = document.getElementsByTagName('head')[0],
		
	// Load as much resources as we can
	loadResources = function(resources) {
		// Waiting for DOM readiness then load resources
		if(!head) {
			setTimeout(function() {
				loadResources(resources);
			}, 50);
		}
		// Load resources
		else if(resources.length) {
			var i = -1,
				resource,
				callback;
			while(resource = resources[++i]) {
				// Resource
				if(typeof resource == 'string') {
					loadResource(resource);
				}
				// Callback
				else if(typeof resource == 'function') {
					callback = resource;
					break;
				}
			}
			watchResources(callback, Array.prototype.slice.call(resources, i+1));
		}
	},

	// Load one resource
	loadResource = function(resource) {
		// Extract resource type
		var implicit_type = /\.(\w+)$/.exec(resource),
			explicit_type = /^\[(\w+)\](.+)/.exec(resource),
			type, node;
		if(explicit_type !== null) {
			type = explicit_type[1];
			resource = explicit_type[2];
		}
		else if(implicit_type !== null) {
			type = implicit_type[1];
		}
		else {
			return;
		}
		// Verify if the resource is not already handled
		if(resource in handled_resources) {
			return;
		}
		// Mark the resource as handled (but not loaded yet)
		handled_resources[resource] = false;
		// Load resource
		switch(type) {
			case 'js':
				// Create SCRIPT element
				node = document.createElement('script');
				node.src = resource;
                node.async = false;
				head.appendChild(node);
				// Watch loading state
				var version = navigator.appVersion.match(/MSIE (\d)/);
				if(version !== null && parseInt(version[1], 10) < 9) {
					// IE<9
					node.onreadystatechange = function() {
						if(/ded|co/.test(this.readyState)) {
							handled_resources[resource] = true;
                            node.onreadystatechange = null;
						}
					};
				}
				else {
					// Other browsers
					node.onload = function() {
						handled_resources[resource] = true;
                        node.onload = null;
					};
				}
				break;
			case 'css':
				// Create LINK element
				node = document.createElement('link');
				node.rel = 'styleSheet';
				node.href = resource;
				head.appendChild(node);
				// Watch loading state
				watchStylesheet(node, resource);
				break;
			default:
				delete handled_resources[resource];
				return;
		}
	},

	// Watch if all resources have been loaded
	watchResources = function(callback, resourcesToLoad) {
		for(var resource in handled_resources) {
			if(!handled_resources[resource]) {
				setTimeout(function() {
					watchResources(callback, resourcesToLoad);
				}, 50);
				return;
			}
		}
		if(typeof callback == 'function') {
			callback();
		}
		loadResources(resourcesToLoad);
	},

	// Watch if a CSS resource has been loaded
	watchStylesheet = function(node, resource) {
		if(node.sheet || node.styleSheet) {
			handled_resources[resource] = true;
		}
		else {
			setTimeout(function() {
				watchStylesheet(node, resource);
			}, 50);
		}
	};
	
	// Load resources
	loadResources(arguments);
}
return Toast;
}));


/***/ }),

/***/ 56:
/***/ (function(module, exports) {

module.exports = Event
function Event() {
    var listeners = []

    return { broadcast: broadcast, listen: event }

    function broadcast(value) {
        var listenersCopy = listeners.slice()
        for (var i = 0; i < listenersCopy.length; i++) {
            if (!listenersCopy[i].deleted) {
                listenersCopy[i].fn(value)
            }
        }
    }

    function event(listener) {
        listeners.push(new ListItem(listener))

        return removeListener

        function removeListener() {
            for (var i = 0; i < listeners.length; i++) {
                if (listeners[i].fn === listener) {
                    listeners[i].deleted = true
                    listeners.splice(i, 1)
                    break
                }
            }
        }
    }
}

function ListItem(fn) {
    this.fn = fn
    this.deleted = false
}


/***/ })

/******/ });